Linked List Cycle

思路一:之间使用hashTable进行判断

/**
 * 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) {
        unordered_map<ListNode *, int> hashTable;
        
        while(head)
        {
            if(hashTable.count(head) > 0)
                return true;
            
            hashTable[head] = 1;
            head = head->next;
        }
        
        return false;
    }
};

思路二:使用两个指针,一个步幅,一个小,若最终相遇则存在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) {
        if(head == nullptr)
            return false;
            
        ListNode *first=head;
        ListNode *second = head->next;
        
        while(second)
        {
            if(first == second)
                return true;
                
            first = first->next;
            if(second->next != nullptr)
            {
                second = second->next->next;
            }
            else
                return false;
        }
        
        return false;
    }
};

 

posted @ 2017-03-24 18:41  chengcy  Views(115)  Comments(0)    收藏  举报