標籤:style blog http color strong io
Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
For 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.
Try to do this in one pass.
演算法:刪除單鏈表的節點一定要找到其前驅節點。
思路1:先求出list的長度,從而在遍曆的時候可以計數,通過計數從而找到其前驅節點,空間時間複雜度都是O(n),但是兩次遍曆,計算list長度的時候,第二遍遍曆的時候。
比較簡單,不再實現了。
思路2,雙指標,讓第二個指標先走n步,然後齊步走,第二個指標走到底的時候,第一個指標剛好停在其前驅,一次遍曆
代碼如下:
1 public class Solution { 2 public ListNode removeNthFromEnd(ListNode head, int n) { 3 ListNode hhead = new ListNode(0); 4 hhead.next = head; 5 ListNode one = hhead; 6 ListNode two = hhead; 7 for(int i = 0; i < n; two = two.next,i++); 8 while(two.next != null){ 9 one = one.next;10 two = two.next;11 }12 one.next = one.next.next;13 return hhead.next;14 }15 }
鏈表題,雙指標真的很常用,甚至是三指標,這道題是很經典的面試題,只不過本題把難度限制了,比如n的大小範圍合法,預設list合法等