LinkedList Cycle (easy)
Problem Statement
Given the head of a Singly LinkedList, write a function to determine if the LinkedList has a cycle in it or not.
Try it yourself
Try solving this question here:
class ListNode {int value = 0;ListNode next;ListNode(int value) {this.value = value;}}class LinkedListCycle {public static boolean hasCycle(ListNode head) {// TODO: Write your code herereturn false;}public static void main(String[] args) {ListNode head = new ListNode(1);head.next = new ListNode(2);head.next.next = new ListNode(3);head.next.next.next = new ListNode(4);head.next.next.next.next = new ListNode(5);head.next.next.next.next.next = new ListNode(6);System.out.println("LinkedList has cycle: " + LinkedListCycle.hasCycle(head));head.next.next.next.next.next.next = head.next.next;System.out.println("LinkedList has cycle: " + LinkedListCycle.hasCycle(head));head.next.next.next.next.next.next = head.next.next.next;System.out.println("LinkedList has cycle: " + LinkedListCycle.hasCycle(head));}}
Solution
Imagine two racers running in a circular racing track. If one racer is faster than the other, the faster racer is bound to catch up and cross the slower racer from behind. We can use this fact to devise an algorithm to determine if a LinkedList has a cycle in it or not.
Imagine we have a slow and a fast pointer to traverse the LinkedList. In each iteration, the slow pointer moves one step and the fast pointer moves two steps. This gives us two conclusions:
- If the LinkedList doesn’t have a cycle in it, the fast pointer will reach the end of the LinkedList before the slow pointer to reveal that there is no cycle in the LinkedList.
- The slow pointer will never be able to catch up to the fast pointer if there is no cycle in the LinkedList.
If the LinkedList has a cycle, the fast pointer enters the cycle first, followed by the slow pointer. ...