Thursday, October 31, 2013

Linked List Cycle II [Leetcode]

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?

Solution: this is a follow-up question of Linked List Cycle; first find out the meeting point by advancing fast pointer 2 steps a time and advancing slow pointer 1 step a time; It is to be noted that the distance between the meeting point and the node where the cycle begins is the same as the distance between the head of the linked list and the node where the cycle begins. Thus, after finding out the meeting point, the only thing we need to do is to move the fast point to the head, and advance both slow and fast points simultaneously 1 step a time; when those two pointers meet again, we get the node where the cycle begins.
//k+pn+x=m; 2m-m=qn; =>k+x=(q-p)n

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(!head || !head->next || !head->next->next)
            return NULL;
        ListNode* slow = head->next;
        ListNode* fast = head->next->next;
        while(slow!=fast){
            if(!fast->next || !fast->next->next)
                return NULL;
            slow=slow->next;
            fast=fast->next->next;
        }
        fast = head;
        while(slow!=fast){
            slow=slow->next;
            fast=fast->next;
        }
        return slow;
    }
};

No comments:

Post a Comment