成人无码视频,亚洲精品久久久久av无码,午夜精品久久久久久毛片,亚洲 中文字幕 日韩 无码

資訊專欄INFORMATION COLUMN

[Lintcode] Nth to Last Node in List 鏈表倒數(shù)第N個節(jié)點

CoXie / 2742人閱讀

摘要:遞歸法復(fù)雜度時間空間思路當(dāng)遞歸到鏈表尾部時返回,每次返回時長度加,一旦長度為時記錄下該節(jié)點。雙指針法復(fù)雜度時間空間思路用兩個指針,快指針先走步,然后快慢指針同時開始走,保持的距離,這樣當(dāng)快指針到達(dá)末尾時,慢指針就是倒數(shù)第個。

Nth to Last Node in List

Find the nth to last element of a singly linked list.

The minimum number of nodes in list is n.

遞歸法 復(fù)雜度

時間 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

相關(guān)文章

  • [LintCode/LeetCode] Nth to Last Node in List

    摘要:依然是一道找倒數(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 ...

    Salamander 評論0 收藏0
  • [LeetCode/LintCode] Remove Nth Node From End of L

    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...

    Jaden 評論0 收藏0
  • LeetCode 19:刪除鏈表倒數(shù)N節(jié)點 Remove Nth Node From End

    摘要:給定一個鏈表,刪除鏈表的倒數(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 ...

    qiangdada 評論0 收藏0
  • LeetCode 19:刪除鏈表倒數(shù)N節(jié)點 Remove Nth Node From End

    摘要:給定一個鏈表,刪除鏈表的倒數(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 ...

    周國輝 評論0 收藏0
  • leetcode19 Remove Nth Node From End of List鏈表中移除

    摘要:雖然時間復(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, ...

    YPHP 評論0 收藏0

發(fā)表評論

0條評論

CoXie

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<