[LeetCode]142.Linked List Cycle II,leetcode142.linked

來源:互聯網
上載者:User

[LeetCode]142.Linked List Cycle II,leetcode142.linked

題目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:
Can you solve it without using extra space?

分析:

首先使用快慢指標技巧,如果fast指標和slow指標相遇,則說明鏈表存在環路。當fast與slow相遇時,slow肯定沒有遍曆完鏈表,而fast已經在環內迴圈了n圈了(1<=n)設slow走了s步,則fast走了2s步(fast步數還等於s加上環在多轉的n圈),設環長為r則:

                    2s = s + nr                    s = nr

設整個鏈長L,環進入點與相遇點距離為a,起點到環進入點距離為x,則:

             x + a = s = nr = (n - 1)r + r = (n - 1)r + L - x             x = (n - 1)r + L - x - a

L -x -a 為相遇點到環進入點的距離,由此可知,從鏈表開頭到環進入點等於n - 1圈內環 + 相遇點到環進入點,於是我們可以從head開始另設一個指標slow2,兩個慢指標每次前進一步,他們兩個一定會在環進入點相遇。

代碼:

    /**------------------------------------    *   日期:2015-02-05    *   作者:SJF0115    *   題目: 142.Linked List Cycle II    *   網址:https://oj.leetcode.com/problems/linked-list-cycle-ii/    *   結果:AC    *   來源:LeetCode    *   部落格:    ---------------------------------------**/    #include <iostream>    #include <vector>    #include <algorithm>    using namespace std;    struct ListNode{        int val;        ListNode *next;        ListNode(int x):val(x),next(NULL){}    };    class Solution {    public:        ListNode *detectCycle(ListNode *head) {            if(head == nullptr){                return nullptr;            }//if            ListNode *slow = head,*fast = head,*slow2 = head;            while(fast != nullptr && fast->next != nullptr){                slow = slow->next;                fast = fast->next->next;                // 相遇點                if(slow == fast){                    while(slow != slow2){                        slow = slow->next;                        slow2 = slow2->next;                    }//while                    return slow;                }//if            }//while            return nullptr;        }    };

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.