程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> [LeetCode]142.Linked List Cycle II

[LeetCode]142.Linked List Cycle II

編輯:關於C++

題目:
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 
    #include 
    #include 
    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;
        }
    };

運行時間

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved