LeetCode--Linked List Cycle

来源:互联网 发布:聊天软件排名 编辑:程序博客网 时间:2024/06/15 17:19

题目:

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,再次出现就是存在循环

0 0
原创粉丝点击