描述
给出一个单链表,返回删除单链表的倒数第 K 个节点的链表。
输入描述:
n 表示链表的长度。
val 表示链表中节点的值。
输出描述:
在给定的函数内返回链表的头指针。
示例1
输入:
5 4
1 2 3 4 5
输出:
1 3 4 5
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] n=in.nextLine().split(" ");//0 1 5 4
String[] num=in.nextLine().split(" ");//0 1 2 3 4 1 2 3 4 5
Node head=trans(num);//把数组变成链表
Node newHead=removeLastKthNode(head,Integer.parseInt(n[1]));
while(newHead!=null){
System.out.print(newHead.value+" ");
newHead=newHead.next;
}
}
//数组转链表
public static Node trans(String[] nums) {
Node head = new Node(Integer.parseInt(nums[0]));
Node cur = head;
for(int i = 1; i < nums.length; i++) {
cur.next = new Node(Integer.parseInt(nums[i]));
cur = cur.next;
}
return head;
}
//删除第k个节点
public static Node removeLastKthNode(Node head,int lastKth){
if(head==null||lastKth<1){
return head;
}
Node cur=head;
while(cur!=null){//k每走一步减1
lastKth--;
cur=cur.next;
}
if(lastKth==0){//k走到最后刚好=0,则倒数第k个是链表的头节点
head=head.next;//第二个节点作为新的头节点,相当于删除头节点
}
if(lastKth<0){//k走到最后<0,需要找到前一个节点
cur=head;//从头节点再走一遍
while(++lastKth!=0){//每走一步 都加1,直到k=0 就找到了前一个节点
cur=cur.next;
}
cur.next=cur.next.next;//指向下下个节点
}
return head;//返回变完的链表,或者是k>0不满足删除条件返回的是原本链表
}
}
class Node{
public int value;
public Node next;
public Node(int value){
this.value=value;
}
}