16. Check if Circular linked list

16. Check if Circular linked list


Problem link :- click here


package Linked_List;

public class LinkedList__16
{

	static Boolean checkIfCircular(LinkedList list)
	{
		if(list.head == null)
			return false;
		
		Node head = list.head;
		Node temp = list.head;
		while(temp.next != head)
		{
			if(temp.next == null)
				break;
			temp = temp.next;
		}
		
		if(temp.next == head)
			return true;
		return false;
	}
	
	public static void main(String[] args)
	{
		LinkedList list = new LinkedList();
		list.push(1);
		list.push(2);
		list.push(3);
		list.push(4);
		list.push(5);
		
		//making the list circular 
		list.head.next.next.next.next.next = list.head;
		
		Boolean ans = checkIfCircular(list);
		if(ans)
			System.out.println("Given linked list is circular");
		else
			System.out.println("Given linked list is not circular");
	}

}

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