049 在链表中删除倒数第K个节点
Table of Contents

ac

import java.util.Scanner;



class ListNode {
    int val;
    ListNode next = null;
    ListNode(int val) {
        this.val = val;
    }
}

public class Main {

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

    public static void main(String[] args) {
        int n = sc.nextInt();
        int k = sc.nextInt();
        ListNode list1 = new ListNode(-1);
        ListNode tail = list1;
        for(int i=0;i<n;i++){
            int val = sc.nextInt();
            ListNode tmp = new ListNode(val);
            tail.next = tmp;
            tail = tmp;
        }
        // 倒数k,正过来第k2
        int k2 = n - k + 1;

        // 找到k2之前的节点
        int k3 = k2 - 1;
        ListNode h2 = list1;
        while (k3 > 0){
            h2 = h2.next;
            k3 --;
        }

        // 删除
        ListNode delNode = h2.next;
        h2.next = delNode.next;

        // 打印
        StringBuilder sb = new StringBuilder();
        boolean flag = false;
        ListNode p = list1.next;
        while (p != null){
            if(!flag) {
//                System.out.print(p.val);
                sb.append(p.val);
                flag = true;
            }else {
//                System.out.print(" " + p.val);
                sb.append(" "+ p.val);
            }
            p = p.next;
        }
        System.out.println(sb.toString());
    }


}
/*
5 4
1 2 3 4 5

1 3 4 5


5 5
1 2 3 4 5
*/