106 删除链表的中间节点-删除第K个
Table of Contents

ac

C

# include <bits/stdc++.h>
using namespace std;

struct list_node{
    int val;
    struct list_node * next;
}; //链表的节点

int K;

list_node * input_list(void) //读入链表
{
    int n, val;
    list_node * phead = new list_node();
    list_node * cur_pnode = phead;
    scanf("%d %d", &n, &K);
    for (int i = 1; i <= n; ++i) {
        scanf("%d", &val);
        if (i == 1) {
            cur_pnode->val = val;
            cur_pnode->next = NULL;
        }
        else {
            list_node * new_pnode = new list_node();
            new_pnode->val = val;
            new_pnode->next = NULL;
            cur_pnode->next = new_pnode;
            cur_pnode = new_pnode;
        }
    }
    return phead;
}

list_node * remove_kth_node(list_node * head, int K)
{
    //////在下面完成代码
    if(K == 1){
        list_node *node = head->next;
        delete head;
        return node;
    }
    list_node *kPre = head;
    K --;
    while(--K>0){
        kPre = kPre->next;
    }
    list_node *rm = kPre->next;
    kPre->next = rm->next;
    delete rm;
    return head;
}

void print_list(list_node * head)
{
    while (head != NULL) {
        printf("%d ", head->val);
        head = head->next;
    }
}

int main ()
{
    list_node * head = input_list(); // 链表的头节点
    list_node * rhead = remove_kth_node(head, K);
    print_list(rhead);
    return 0;
}

java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

class Node{
    public int val;
    public Node next;
    public Node(int _val){
        val=_val;
        next = null;
    }
}

public class Main {
    public static Scanner sc = new Scanner(System.in);

    public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws Exception {
        Node head = new Node(-1);
        Node tail = head;
        int n = sc.nextInt();
        int k = sc.nextInt();
        for(int i=0;i<n;i++){
            int val = sc.nextInt();
            Node node = new Node(val);
            tail.next = node;
            tail = node;
        }

        Node delNodePre = head;
        while (--k > 0){
            delNodePre = delNodePre.next;
        }
        // free
        delNodePre.next = delNodePre.next.next;

        boolean flag = true;
        Node p = head.next;
        while (p != null){
            if(flag) {
                System.out.print(p.val);
                flag = false;
            }else {
                System.out.print(" " + p.val);
            }
            p = p.next;
        }
        System.out.println();
    }
}
/*

 */