Given head
, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next
pointer. Internally, pos
is used to denote the index of the node that tail's next
pointer is connected to. Note that pos
is not passed as a parameter.
Return true
if there is a cycle in the linked list. Otherwise, return false
.
Solutions:
(1) Hash table: save the nodes that have already been seen.
Time: O(n); Space: O(n)
Java:
public boolean hasCycle(ListNode head) {
Set<ListNode> nodesSeen = new HashSet<>();
while (head != null) {
if (nodesSeen.contains(head)) {
return true;
} else {
nodesSeen.add(head);
}
head = head.next;
}
return false;
}
// https://leetcode.com/problems/linked-list-cycle/solution/
(2) Two Pointers: Fast & slow pointers must meet in a loop
Java:
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}
// https://leetcode.com/problems/linked-list-cycle/solution/
public boolean hasCycle(ListNode head) {
if(head==null) return false;
ListNode walker = head;
ListNode runner = head;
while(runner.next!=null && runner.next.next!=null) {
walker = walker.next;
runner = runner.next.next;
if(walker==runner) return true;
}
return false;
}
// https://leetcode.com/problems/linked-list-cycle/discuss/44489/O(1)-Space-Solution
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode walker = head;
ListNode runner = head;
while(runner!=null && runner.next!=null) {
walker = walker.next;
runner = runner.next.next;
if(walker==runner) return true;
}
return false;
}
}
Python:
def hasCycle(self, head):
try:
slow = head
fast = head.next
while slow is not fast:
slow = slow.next
fast = fast.next.next
return True
except:
return False
# https://leetcode.com/problems/linked-list-cycle/discuss/44494/Except-ionally-fast-Python
C++:
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL || head -> next == NULL)
return false;
ListNode *fast = head;
ListNode *slow = head;
while(fast -> next && fast -> next -> next){
fast = fast -> next -> next;
slow = slow -> next;
if(fast == slow)
return true;
}
return false;
}
};
//https://leetcode.com/problems/linked-list-cycle/discuss/44604/My-faster-and-slower-runner-solution
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast) {
return true;
}
}
return false;
}
};
// with no need to check