I have written a program which checks whether the entered list is a circular list or not. I am successfully able to make the circular list. But as soon as I call the check_circular fucntion my program hangs. Can anybody find the error please? And yes the programs hangs when the list is circular and I call check_circular function. The check_circular function executes properly if the list is not circular.
I am using gcc compiler!
#include<stdio.h>
#include<malloc.h>
int n;
struct node
{
int data;
struct node *next;
};
struct node *newnode,*temp,*temp2,*start=NULL,*x, *temp3, *temp4;
void create()
{
int i;
printf("Enter the no. of nodes you want to insert");
scanf("%d", &n);
for(i=0; i<n; i++)
{
newnode=malloc(sizeof(struct node));
printf("\n Enter the data ");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(start==NULL)
start=newnode;
else
{
for(temp=start;temp->next!=NULL;temp=temp->next);
temp->next=newnode;
}
}
}
void display()
{
if(start==NULL)
{
printf("\n Linklist is EMPTY ");
}
else
{
printf("The entered list is:");
for(temp=start;temp!=NULL;temp=temp->next)
{
printf("\n %d",temp->data);
}
}
}
void make_circular()
{
int i,pos;
printf("\n Enter the node no at which you want to connect the list to make it circular (-1 to leave as it is) ");
scanf("%d",&pos);
if(pos>n)
{
printf("Invalid position");
}
else if(pos==-1)
return;
else
{
for(temp=start;temp->next!=NULL;temp=temp->next);
temp2=start;
printf("After temp2");
for(i=1; i<pos; i++)
temp2=temp2->next;
temp->next=temp2;
}
}
void check_circular()
{
temp3=start;
while(temp3!=NULL)
{
temp4=temp3->next;
while(temp4!=NULL)
{
if(temp4==temp3)
{
printf("List is circular");
return;
}
temp4=temp4->next;
}
temp3=temp3->next;
}printf("List is not circular");
}
int main()
{
create();
display();
make_circular();
check_circular();
//display();
return 0;
}