Given a list, return the node where the cycle begins. If there is no cycle, return null

Consider example 1->2->3->4->1 returns 1.

Consider example 1->2->3->4 returns null.

The problem can be solved by having slow and fast pointer.

  • Increment slow pointer once and increment fast pointer twice.
  • Check whether the node at slow and fast pointer is same.
  • If the nodes are same, move the slow pointer to start of the list.
  • Increment slow and fast pointer. Check the nodes, if its same return the node.

The LinkedList for the example is singly. Here is how Node class looks like:

class Node {
	int value;
	public Node next;
	public Node(int value) {
		this.value = value;

public class LinkedListCycle {

	public boolean hasCycle(Node head) {
        if(head==null) return false;
		Node slow = head;
		Node fast = head;
		boolean isCycle = false;
		while( != null && != null) {
			slow =;
			fast =;
			if(slow == fast) {
				isCycle = true;
		if (!isCycle)
			return null;
		fast = head;
		while (slow != fast) {
			slow =;fast =;
		return fast;	

Subscribe to get latest updates.

© 2016 Java Questions | Sitemap