The Linked List Cycle solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Linked List Cycle
C++, Python and TypeScript solutions for Linked List Cycle.
Solution files
Python•linked-list-cycle/synced-solution.py
class 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
C++•linked-list-cycle/synced-solution.cpp
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;
}
};
TypeScript•linked-list-cycle/synced-solution.ts
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;
}