Improve Algorithm Skills.

PHOTO EMBED

Fri Feb 24 2023 09:24:24 GMT+0000 (Coordinated Universal Time)

Saved by @mtommasi

Implement a method to detect if a linked list has a cycle.
typescript
Copy code
function hasCycle<T>(head: Node<T> | null): boolean {
  let slow = head;
  let fast = head;
  while (fast !== null && fast.next !== null) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow === fast) {
      return true;
    }
  }
  return false;
}

// Example usage:
const list = new LinkedList<number>();
list.add(1);
list.add(2);
list.add(3);
list.head.next.next.next = list.head;
console.log(hasCycle(list.head)); // Output: true
content_copyCOPY

https://chat.openai.com/chat