1. 程式人生 > >[LeetCode]19. Remove Nth Node From End of List刪除連結串列的倒數第N個節點

[LeetCode]19. Remove Nth Node From End of List刪除連結串列的倒數第N個節點

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

 

題目要求刪除一個節點,但是給出的是倒數的節點,如果是正數的節點一次遍歷過去就可以了,但是倒數的節點似乎不能這麼做。

其實還是可以一次遍歷刪除節點,我們先設定一個指標i,往前推n個,這個時候再設定第二個指標j,兩個指標i和j同時往前推,這樣當

i抵達連結串列結尾時j的位置正好是倒數第n個節點,此時把節點j刪除就可以了(測試樣例中有個特殊例子,輸入[1],這裡要特殊化處理)

/**
 * 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 res=new ListNode(0); res.next=head; ListNode l1=res; ListNode l2=res; for(int i=1;i<=n+1;i++){ l1=l1.next; } while(l1!=null){ l2=l2.next; l1
=l1.next; } l2.next=l2.next.next; return res.next; } }