Try   HackMD

141. Linked List Cycle


My Solution

Solution 1

The Key Idea for Solving This Coding Question

Use hash set to record the visited nodes. Once find a visited node in the hash set, there is a cycle in the linked list.

C++ Code

/** * 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) { if (head == nullptr || head->next == nullptr) { return false; } unordered_set<ListNode *> visited; for (ListNode *it = head; it != nullptr; it = it->next) { auto iter = visited.find(it); if (iter != visited.end()) { // This node has been visited. Cycle detected! return true; } visited.insert(it); } return false; } };

Time Complexity

O(n)
n
is the number of nodes in the linked list referred by head.

Space Complexity

O(n)

Solution 2 (Floyd Cycle Detection Algorithm)

The Key Idea for Solving This Coding Question

C++ Code

/** * 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) { ListNode *fast = head, *slow = head; while (fast != nullptr && fast->next != nullptr) { slow = slow->next; fast = fast->next->next; if (fast == slow) { return true; } } return false; } };

Time Complexity

O(n)
n
is the number of nodes in the linked list referred by head.

Space Complexity

O(1)

Solution 3

The Key Idea for Solving This Coding Question

C++ Code

/** * 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) { if (head == nullptr) { return false; } ListNode *curr = new ListNode(), *x = head->next; for (ListNode *it = head; it != nullptr; it = x) { if (it->next == curr) { return true; } x = it->next; it->next = curr; } return false; } };

Time Complexity

O(n)
n
is the number of nodes in the linked list referred by head.

Space Complexity

O(1)

Solution 4 (Brent Cycle Detection Algorithm)

The Key Idea for Solving This Coding Question

C++ Code

/** * 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) { if (head == nullptr) { return false; } ListNode *fast = head, *slow = head; unsigned long steps = 2; while (fast != nullptr) { for (unsigned long i = 0; i < steps && fast != nullptr; ++i) { fast = fast->next; if (fast == slow) { return true; } } steps *= 2; slow = fast; } return false; } };

Time Complexity

O(n)
n
is the number of nodes in the linked list referred by head.

Space Complexity

O(1)

Reference

探索 Floyd Cycle Detection Algorithm

Miscellaneous