top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to identify linked list is circular?

0 votes
879 views

How to identify linked list is circular? Please share the sample code?

posted Mar 18, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

+1 vote
 
Best answer

To check whether it is circular or not pass the head or start node address to following function:

void CheckListIsCircularOrNot(struct node *head)
{
    struct node *temp=NULL;
    temp=head;
    while(temp!=NULL)
    {
      if(temp->next==head)
      {
       printf("List is circular ");
       break;
      }
      else
      {
       temp=temp->next;
      }
    }
}
answer Mar 18, 2016 by Shivam Kumar Pandey
0 votes

If the last element of linkedlist is not empty but it carries the address of start element ,then our linkedlist will be circular..

answer Mar 19, 2016 by Ajay Kumar Topno
How will u find the last node in circular LL?
for eg..

struct node{
int data;
struct node *next;
}; struct node * start=NULL;

void check()
{
struct  node * temp;
temp=start;
while(temp!=NULL)
{
temp=temp->next;
if(temp->next==start)
{
printf("linkedlist is circular");
}
else{
temp=temp->next;
}
}
0 votes
//Note: Cycle may be generated any node in Linked list , So this problem can be solved by Floyd's cycle finding algorithm
// C program to detect loop in a linked list using Floyd's cycle finding algorithm

int detectcycleinLL(struct node *list)
{
    struct node  *slow_p = list, *fast_p = list;

    while (slow_p && fast_p && fast_p->next )
    {
        slow_p = slow_p->next;
        fast_p  = fast_p->next->next;
        if (slow_p == fast_p)
        {
           printf("Found Loop");
           return 1;
        }
    }
    return 0;
}
answer Mar 20, 2016 by Rajan Paswan
...