15 Jun 2024C++ / Python / TypeScriptEasy

Linked List Cycle

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.

solution files

  • C++ linked-list-cycle/synced-solution.cpp
  • Python linked-list-cycle/synced-solution.py
  • TypeScript linked-list-cycle/synced-solution.ts

Solution files

Pythonlinked-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;
    }
};
TypeScriptlinked-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;
}