很明顯是快慢指針?lè)梢詫?xiě)的,這個(gè)不是難點(diǎn)领虹,要注意的是规哪,如果要?jiǎng)h除第一個(gè)節(jié)點(diǎn),快指針會(huì)已經(jīng)跑到了null塌衰,所以如果當(dāng)快指針到了null,n還沒(méi)有減完的話诉稍,就是要?jiǎng)h除頭節(jié)點(diǎn)。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fast=head;
ListNode slow =head;
while(n>=0){
if(fast==null) return slow.next;
fast=fast.next;
n--;
}
while(fast!=null){
fast=fast.next;
slow=slow.next;
}
slow.next=slow.next.next;
return head;
}
}