...

/

Start of LinkedList Cycle (medium)

Start of LinkedList Cycle (medium)

Problem Statement

Given the head of a Singly LinkedList that contains a cycle, write a function to find the starting node of the cycle.

Try it yourself

Try solving this question here:

class ListNode {
int value = 0;
ListNode next;
ListNode(int value) {
this.value = value;
}
}
class LinkedListCycleStart {
public static ListNode findCycleStart(ListNode head) {
// TODO: Write your code here
return head;
}
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);
head.next.next.next.next.next.next = head.next.next;
System.out.println("LinkedList cycle start: " + LinkedListCycleStart.findCycleStart(head).value);
head.next.next.next.next.next.next = head.next.next.next;
System.out.println("LinkedList cycle start: " + LinkedListCycleStart.findCycleStart(head).value);
head.next.next.next.next.next.next = head;
System.out.println("LinkedList cycle start: " + LinkedListCycleStart.findCycleStart(head).value);
}
}

Solution

If we know the length of the LinkedList cycle, we can find the start of the cycle through the following steps:

  1. Take two pointers. Let’s call them pointer1 and pointer2.
  2. Initialize both pointers to point to the start of the LinkedList.
  3. We can find the length of the LinkedList cycle using the approach discussed in LinkedList Cycle. Let’s assume that the length of the cycle is ‘K’ nodes.
  4. Move
...