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?

老题,没难度。

/**
 * 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) {
        ListNode *fast,*slow;
        if(head == NULL||head->next==NULL||head->next->next==NULL)return NULL;
        fast =head->next->next;
        slow =head->next;
        if(fast == NULL ||slow == NULL)return NULL;
        while(fast!=slow)
        {
            if(fast == NULL ||slow == NULL)return NULL;
            fast = fast->next;
            if(fast == NULL)return NULL;
            fast = fast->next;
            slow = slow->next;
        }
        fast = head;
        while(fast!=slow)
        {
            fast=fast->next;
            slow=slow->next;
        }
        return slow;
    }
};

  

posted on 2014-03-26 16:30  pengyu2003  阅读(95)  评论(0编辑  收藏  举报

导航