摘要:題目詳情題目要求輸入一個和一個數(shù)字。要求我們返回刪掉了倒數(shù)第個節(jié)點的鏈表。想法求倒數(shù)第個節(jié)點,我們將這個問題轉化一下。我們聲明兩個指針和,讓和指向的節(jié)點距離差保持為。解法使點和點的差距為同時移動和使得到達的末尾刪除倒數(shù)第個節(jié)點
題目詳情
Given a linked list, remove the nth node from the end of list and return its head.想法題目要求輸入一個linked list 和一個數(shù)字n。要求我們返回刪掉了倒數(shù)第n個節(jié)點的鏈表。
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.
求倒數(shù)第n個節(jié)點,我們將這個問題轉化一下。
我們聲明兩個指針low和fast,讓fast和low指向的節(jié)點距離差保持為n。
這樣當fast指向了鏈表中的最后一個節(jié)點時,low指針指向的節(jié)點就是我們所求的倒數(shù)第n個節(jié)點了。
解法public ListNode removeNthFromEnd(ListNode head, int n) { ListNode start = new ListNode(0); ListNode slow = start , fast = start; slow.next = head; //使fast點和slow點的差距為n for(int i=1;i<=n+1;i++){ fast = fast.next; } //同時移動fast和slow 使得fast到達listnode的末尾 while(fast != null){ slow = slow.next; fast = fast.next; } //刪除倒數(shù)第n個節(jié)點 slow.next = slow.next.next; return start.next; }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉載請注明本文地址:http://m.hztianpu.com/yun/68762.html
摘要:雖然時間復雜度還是但是顯然我們可以再一次遍歷中完成這個任務?,F(xiàn)在跳出下標的思路,從另一個角度分析??炻?jié)點之間的距離始終是。當快節(jié)點到達終點時,此時的慢節(jié)點就是所要刪去的節(jié)點。 題目要求 Given a linked list, remove the nth node from the end of list and return its head. For example, ...
摘要:這題也是攜程年暑假實習生的筆試題。最開始想的解法就是,先循環(huán)求鏈表的長度,再用長度,再循環(huán)一次就能移除該結點。結果對的,但是超時了。再返回整個鏈表。 Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2...
摘要:第題給定一個鏈表,刪除鏈表的倒數(shù)第個節(jié)點,并且返回鏈表的頭結點。因為,若有一個真正的頭結點,則所有的元素處理方式都一樣。但以第一個有效元素為頭結點,就導致算法的不一致,需要單獨處理第一個有效元素頭結點。 leetcode第19題 Given a linked list, remove the n-th node from the end of list and return its h...
摘要:給定一個鏈表,刪除鏈表的倒數(shù)第個節(jié)點,并且返回鏈表的頭結點。示例給定一個鏈表和當刪除了倒數(shù)第二個節(jié)點后,鏈表變?yōu)檎f明給定的保證是有效的。值得注意的的是,指向應當刪除的節(jié)點并無法刪除它,應當指向該刪除節(jié)點的前一個節(jié)點。 給定一個鏈表,刪除鏈表的倒數(shù)第 n 個節(jié)點,并且返回鏈表的頭結點。 Given a linked list, remove the n-th node from the ...
摘要:給定一個鏈表,刪除鏈表的倒數(shù)第個節(jié)點,并且返回鏈表的頭結點。示例給定一個鏈表和當刪除了倒數(shù)第二個節(jié)點后,鏈表變?yōu)檎f明給定的保證是有效的。值得注意的的是,指向應當刪除的節(jié)點并無法刪除它,應當指向該刪除節(jié)點的前一個節(jié)點。 給定一個鏈表,刪除鏈表的倒數(shù)第 n 個節(jié)點,并且返回鏈表的頭結點。 Given a linked list, remove the n-th node from the ...
閱讀 440·2023-04-25 16:38
閱讀 1575·2021-09-26 09:46
閱讀 3414·2021-09-08 09:35
閱讀 2837·2019-08-30 12:54
閱讀 3307·2019-08-29 17:06
閱讀 1109·2019-08-29 14:06
閱讀 3417·2019-08-29 13:00
閱讀 3526·2019-08-28 17:53