3. Detect loop in linked list

3. Detect loop in linked list


Problem link :- click here


package Linked_List;

public class LinkedList__3
{
	static Boolean detectALoop(LinkedList list)
	{
		if(list.head == null   ||    list.head.next == null)
			return false;
		
		Node slow = list.head;
		Node fast = list.head;
		
		while(fast.next != null  &&   fast.next.next != null)
		{
			slow = slow.next;
			fast = fast.next.next;
        			
        		if(fast.data == slow.data)
        			return true;
		}
		
		return false;
	}
	
	public static void main(String[] args)
	{
		LinkedList list = new LinkedList();
		list.push(1);
		list.push(8);
		list.push(3);
		list.push(4);
		
		//creating a loop
		Node node = list.head.next.next.next;
		node.next = list.head.next;
		
		Boolean ans = detectALoop(list);
		if(ans)
			System.out.println("Loop is present");
		else
			System.out.println("Loop is not present");
	}

}

Time complexity :- O(n)
Space complexity :- O(1)

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree