Linked List Cycle

mail@pastecode.io avatar
unknown
c_cpp
15 days ago
598 B
2
Indexable
Never
/**
 * 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) {
        std::unordered_map<int,int> concurrence;
        while(head!=nullptr)
        {
            size_t address = reinterpret_cast<size_t>(head);
            if(concurrence.count(address))
            {
                return true;
            }
            concurrence[address]=1;
            head=head->next;
        }
        return false;
    }
};
Leave a Comment