[LeetCode]19. Remove Nth Node From End of List刪除鏈表的倒數第N個節點
阿新 • • 發佈:2019-01-08
指針 ext 但是 res bec pan [1] note urn
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; } }
[LeetCode]19. Remove Nth Node From End of List刪除鏈表的倒數第N個節點