题目大意:删除单链表中倒数第n个节点。例子如下:
法一:双指针,fast指针先走n步,然后slow指针与fast一起走,记录slow前一个节点,当fast走到链表结尾,slow所指向的指针就是所找的节点。代码如下(耗时8ms):
1 public ListNode removeNthFromEnd(ListNode head, int n) { 2 int cnt = 0; 3 ListNode fast = head, slow = head, preSlow = head; 4 while(cnt < n) { 5 fast = fast.next; 6 cnt++; 7 } 8 while(fast != null) { 9 fast = fast.next; 10 preSlow = slow; 11 slow = slow.next; 12 } 13 //删除的是第一个节点 14 if(preSlow == slow) { 15 head = preSlow.next; 16 } 17 //删除的不是第一个节点 18 preSlow.next = slow.next; 19 return head; 20 }