[LeetCode] Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

 

Hide Tags
 Linked List Two Pointers
 
 
分析:经典的快慢指针法:
 
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    public:
        bool hasCycle(ListNode *head)
        {   
            if(head == NULL)
                return false;

            ListNode* slow = head->next;
            ListNode* fast = NULL;

            if(slow)
                fast = slow->next;

            while(fast && slow)
            {   
                if(fast == slow)
                    return true;
                if(fast->next && fast->next->next)
                    fast = fast->next->next;
                else //reach the end
                    return false;
                slow = slow->next;
            }   
            return false;
        }   
};

 

 
posted @ 2015-06-23 16:13  穆穆兔兔  阅读(196)  评论(0编辑  收藏  举报