Friday, June 18, 2021
Home coding Write a program to check linkedlist is circular or not.

Write a program to check linkedlist is circular or not.

Given a linkedlist, we have to check a linkedlist is circular or not.

Example:

Input:1 2 3 4 5 6 1
Output:true

Logic:

STEP 1:start traversing a linkedlist till reach its end .
STEP 2:if last node is pointing to first node of linkedlist
STEP 3:then it is circular otherwise or not.

Code

bool CheckCircular(struct Node *head) 
{ 
    if (head == NULL) 
    {
       return true; 
  
    }
    struct Node *temp = head->next; //first node
    while (temp!= NULL&&temp != head) //checking till you reach end 
    {
       node = node->next; 
    }
   if(temp==head)
   {
       return true;
   }
   else
   {
       return false;
   }
} 

Ouput:

true

Time Complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments