Home | Projects | Notes > Problem Solving > LC - E - 141. Linked List Cycle (unordered_set, Floyd's Cycle Detection Algorithm - Two Pointers)
This solution uses STL unordered_set container.
Complexity Analysis:
unordered_set container
Solution:
xxxxxxxxxx251/**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode(int x) : val(x), next(NULL) {}7 * };8 */9class Solution {10public:11 bool hasCycle(ListNode *head) {12 set<ListNode*> s;13
14 while (head)15 {16 if (s.find(head) != s.end())17 return true;18 19 s.insert(head);20 head = head->next;21 }22 23 return false; 24 }25};
This solution uses the Floyd's Cycle Detection Algorithm; the Two Pointers approach. A fast pointer and a slow pointer are used to determine if there exists a cycle in the loop.
The slow pointer moves one node ahead at a time.
The fast pointer moves two nodes ahead at a time.
If a loop exists in the linked list, the fast and slow pointers are bound to meet at some point.
Complexity Analysis:
s
Solution:
xxxxxxxxxx261/**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode(int x) : val(x), next(NULL) {}7 * };8 */9class Solution {10public:11 bool hasCycle(ListNode *head) {12 ListNode *slow = head;13 ListNode *fast = head;14
15 while (fast && fast->next && fast->next->next)16 {17 slow = slow->next;18 fast = fast->next->next;19
20 if (slow == fast)21 return true;22 }23
24 return false;25 }26};