LeetCode--Linked List Cycle

题目:

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

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

    bool hasCycle(ListNode *head) {
        if(head == NULL)
        {
            return false;
        }
        else
        {
            unordered_map<ListNode*, bool> uMap;
            uMap[head] = true;
            ListNode* ptr = head->next;
            while(ptr != NULL)
            {
                if(uMap.count(ptr) > 0)
                    return true;
                uMap[ptr] = true;
                ptr = ptr->next;
            }
            return false;
        }
        
        
    }
将每个出现的Node加入map,再次出现就是存在循环

posted on 2015-11-03 19:31  小二杰  阅读(96)  评论(0编辑  收藏  举报

导航