lintcode-103

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins. 
     *           if there is no cycle, return null
     */
    ListNode *detectCycle(ListNode *head) {
        // write your code here
        map<ListNode*,bool> cnt;
        ListNode *p=head;
        while(p){
            if(!cnt[p])
                cnt[p]=true;
            else
                return p;
            p=p->next;
        }
        return NULL;
    }
};

你可能感兴趣的:(lintcode-103)