程序员代码面试指南第二版 13.在链表中删除倒数第K个节点
题目描述
题目描述
给出一个单链表,返回删除单链表的倒数第 K 个节点的链表。
输入描述:
n 表示链表的长度。
val 表示链表中节点的值。
输出描述:
在给定的函数内返回链表的头指针。
示例1
输入
5 4
1 2 3 4 5
输出
1 3 4 5
第一次做, 倒数第k个节点可能是头结点, 不妨创建一个临时头结点, 指向真正的头结点, 这样就不用区分头结点和非头结点去处理了
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int n = Integer.parseInt(s.split(" ")[0]);
int k = Integer.parseInt(s.split(" ")[1]);
String[] str = sc.nextLine().split(" ");
int[] arr = new int[n];
ListNode head = new ListNode(0);
ListNode curr = head, left;
for(int i=0; i<n; i++){
arr[i] = Integer.parseInt(str[i]);
curr.next = new ListNode(arr[i]);
curr = curr.next;
}
left = head;
curr = head.next;
ListNode right = head.next;
for(int i=0; i<k-1; i++){
right = right.next;
if(right == null)
return;
}
while(right.next != null){
left = curr;
right = right.next;
curr = curr.next;
}
left.next = curr.next;
curr = head.next;
while(curr!=null){
System.out.print(curr.val+" ");
curr = curr.next;
}
}
public static class ListNode{
int val;
ListNode next = null;
ListNode(int val){
this.val = val;
}
}
}