思路:快慢指针,两个指针速度相同,只是间隔一定距离。快指针先前进 k个元素,然后两个指针同样速度前进。这样当快指针到达链表尾部时,慢指针正好到达链表的倒数第k 个元素

public ListNode removeNthFromEnd(ListNode head, int k){
ListNode fast = head;
for(int i = 0; i < k; i++){
fast=fast.next;
}
ListNode curr = head;
ListNode prev = null;
while (fast != null){
prev=curr;
curr=curr.next;
fast=fast.next;
}
if (prev == null) {
head = curr.next;
}
else{
prev.next = curr.next;
}
return head;
};
398

被折叠的 条评论
为什么被折叠?



