leetcode : 19 题。
思路:定义快慢指针,让快指针先走n步,如何同时移动快慢指针,当快指针走到尾时,慢指针刚好是倒数第n个元素(的前一个)。
例:删除倒数第二个节点。n=2;
slow fast
↓ ↓
a->b->c->d->e->null
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
var dummyHead = new ListNode();
dummyHead.next = head;
var slow = dummyHead;
var fast = dummyHead;
//先将fast移动n步
while(n > 0 && fast.next != null)
{
fast = fast.next;
n--;
}
//同时移动 fast slow
while(fast.next != null)
{
fast=fast.next;
slow =slow.next;
}
slow.next = slow.next.next;
return dummyHead.next;
}
}