[leetcode]Remove Nth Node From End of List

來源:互聯網
上載者:User

標籤: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合法等

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.