要求:只能用一趟扫描实现 示例 1: 输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1 输出:[]
示例 3:
输入:head = [1,2], n = 1 输出:[1]
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyhead=new ListNode(0);
dummyhead.next=head;
ListNode slow=dummyhead;
ListNode fast=dummyhead;
while(n+1>0){
fast=fast.next;
n--;
}
while(fast!=null){
fast=fast.next;
slow=slow.next;
}
slow.next=slow.next.next;
return dummyhead.next;
}
解题:设置快慢指针,先让快指针走n+1步,之后让快慢指针同时后移,直到快指针指向空,此时慢指针指向要删除元素的前一个结点。