摘要:遞歸法復(fù)雜度時間空間思路當(dāng)遞歸到鏈表尾部時返回,每次返回時長度加,一旦長度為時記錄下該節(jié)點。雙指針法復(fù)雜度時間空間思路用兩個指針,快指針先走步,然后快慢指針同時開始走,保持的距離,這樣當(dāng)快指針到達(dá)末尾時,慢指針就是倒數(shù)第個。
Nth to Last Node in List
遞歸法 復(fù)雜度Find the nth to last element of a singly linked list.
The minimum number of nodes in list is n.
時間 O(N) 空間 O(N)
思路當(dāng)遞歸到鏈表尾部時返回,每次返回時長度加1,一旦長度為N時記錄下該節(jié)點。
雙指針法 復(fù)雜度時間 O(N) 空間 O(1)
思路用兩個指針,快指針先走N步,然后快慢指針同時開始走,保持N的距離,這樣當(dāng)快指針到達(dá)末尾時,慢指針就是倒數(shù)第N個。
代碼public class Solution { ListNode nthToLast(ListNode head, int n) { // write your code here ListNode slow = head; ListNode fast = head; while(n-- > 0){ fast = fast.next; } while(fast != null){ fast = fast.next; slow = slow.next; } return slow; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://m.hztianpu.com/yun/64520.html
摘要:依然是一道找倒數(shù)第個結(jié)點的鏈表題,用雙指針做。先走,然后和一起走,直到為,的位置就是倒數(shù)第個位置。 Problem Find the nth to last element of a singly linked list. The minimum number of nodes in list is n. Example Given a List 3->2->1->5->null ...
Problem Given a linked list, remove the nth node from the end of list and return its head. Example Given linked list: 1->2->3->4->5->null, and n = 2. After removing the second node from the end, the l...
摘要:給定一個鏈表,刪除鏈表的倒數(shù)第個節(jié)點,并且返回鏈表的頭結(jié)點。示例給定一個鏈表和當(dāng)刪除了倒數(shù)第二個節(jié)點后,鏈表變?yōu)檎f明給定的保證是有效的。值得注意的的是,指向應(yīng)當(dāng)刪除的節(jié)點并無法刪除它,應(yīng)當(dāng)指向該刪除節(jié)點的前一個節(jié)點。 給定一個鏈表,刪除鏈表的倒數(shù)第 n 個節(jié)點,并且返回鏈表的頭結(jié)點。 Given a linked list, remove the n-th node from the ...
摘要:給定一個鏈表,刪除鏈表的倒數(shù)第個節(jié)點,并且返回鏈表的頭結(jié)點。示例給定一個鏈表和當(dāng)刪除了倒數(shù)第二個節(jié)點后,鏈表變?yōu)檎f明給定的保證是有效的。值得注意的的是,指向應(yīng)當(dāng)刪除的節(jié)點并無法刪除它,應(yīng)當(dāng)指向該刪除節(jié)點的前一個節(jié)點。 給定一個鏈表,刪除鏈表的倒數(shù)第 n 個節(jié)點,并且返回鏈表的頭結(jié)點。 Given a linked list, remove the n-th node from the ...
摘要:雖然時間復(fù)雜度還是但是顯然我們可以再一次遍歷中完成這個任務(wù)。現(xiàn)在跳出下標(biāo)的思路,從另一個角度分析??炻?jié)點之間的距離始終是。當(dāng)快節(jié)點到達(dá)終點時,此時的慢節(jié)點就是所要刪去的節(jié)點。 題目要求 Given a linked list, remove the nth node from the end of list and return its head. For example, ...
閱讀 1495·2021-10-14 09:43
閱讀 1059·2021-09-10 10:51
閱讀 1515·2021-09-01 10:42
閱讀 2264·2019-08-30 15:55
閱讀 637·2019-08-30 15:55
閱讀 2409·2019-08-30 14:21
閱讀 1778·2019-08-30 13:04
閱讀 3549·2019-08-29 13:09