1. 程式人生 > >[LeetCode] Linked List Cycle II 單鏈表中的環之二

[LeetCode] Linked List Cycle II 單鏈表中的環之二

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?

這個求單鏈表中的環的起始點是之前那個判斷單鏈表中是否有環的延伸,可參見我之前的一篇文章 (http://www.cnblogs.com/grandyang/p/4137187.html). 還是要設快慢指標,不過這次要記錄兩個指標相遇的位置,當兩個指標相遇了後,讓其一指標從連結串列頭開始,一步兩步,一步一步似爪牙,似魔鬼的步伐。。。哈哈,打住打住。。。此時再相遇的位置就是連結串列中環的起始位置。程式碼如下:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) break;
        }
        
if (!fast || !fast->next) return NULL; slow = head; while (slow != fast) { slow = slow->next; fast = fast->next; } return fast; } };