auto-generated entry for Linked List Cycle. the solution files are available below.
solution files
- C++
linked-list-cycle/synced-solution.cpp - Python
linked-list-cycle/synced-solution.py - TypeScript
linked-list-cycle/synced-solution.ts
Collected C++, Python, TypeScript solutions for linked list cycle. Add a dedicated write-up later if you want deeper notes.
auto-generated entry for Linked List Cycle. the solution files are available below.
linked-list-cycle/synced-solution.cpplinked-list-cycle/synced-solution.pylinked-list-cycle/synced-solution.tsclass Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
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;
}
};
function hasCycle(head: ListNode | null): boolean {
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow!.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}