Linked List Cycle II problem results
First Blood
Saving the visited node in an unordered_set, stop when meeting the same node.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
ListNode *detectCycle(ListNode *head) {
if(head == nullptr)
return head;
unordered_set<ListNode*> visited_node;
while(head->next != nullptr && visited_node.find(head->next) == visited_node.end())
{
visited_node.insert(head);
head = head->next;
}
return head->next;
}
}