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
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter