Leetcode::Linked List Cycle

思想:使用两个指针,一个指针每次走一步,另一个每次走两步,如果走两步的追上走一步的指针,则存在环。

/**
 * 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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        bool result = false;
        
        if( head )
        {
            ListNode * first = head;
            ListNode * second = head;
            
            do
            {
                first = first->next;
                
                if( second->next == NULL || second->next->next == NULL )
                    return result;
                    
                second = second->next->next;
                
            }while( first != second );
            
            result = true;
        }
        
        return result;
    }
};

  

posted @ 2013-10-30 10:18  NinaGood  阅读(152)  评论(0编辑  收藏  举报