Linked List Cycle II

思路一:直接使用hashTable

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

 思路二:http://bookshadow.com/weblog/2015/07/10/leetcode-linked-list-cycle-ii/

/**
 * 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 *first = head;
        ListNode *second = head;
        
        while(first && first->next)
        {
            first = first->next->next;
            second = second->next;
            if(first == second)
            {
                second = head;
                while(first != second)
                {
                    first = first->next;
                    second = second->next;
                }
                return first;
            }
        }
        
        return nullptr;
    }
};

 

posted @ 2017-03-25 13:11  chengcy  Views(112)  Comments(0)    收藏  举报