Linked List Cycle
/** * 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