Reputation: 6053
Here is the link to the code I wrote for circular linked list. The code is pasted below also.
typedef struct node
{
int value;
struct node *next;
}mynode;
mynode *head, *tail, *temp,*sp,*fp;
void add(int value);
void iterative_reverse();
void print_list();
void findcycle();
int main()
{
head=(mynode *)0;
add(1);
add(2);
add(3);
//print_list();
findcycle();
return(0);
}
void add(int value)
{
temp = (mynode *) malloc(sizeof(struct node));
temp->value=value;
temp->next=(mynode *)0;
if(head==(mynode *)0)
{
head=temp;
tail=temp;
}
else
{
tail->next=temp;
tail=temp;
tail->next=head;
temp->next=head;
}
}
void findcycle()
{
if (head == NULL || head->next == NULL)
printf("null");
sp=head;
fp=head->next;
while (fp != NULL && fp->next != NULL)
{
if ((fp == sp) || (fp->next == sp))
printf("Cycle");
sp = sp->next;
fp = fp->next->next;
}
printf("Not a Cycle");
}
void print_list()
{
for(temp=head; temp!=tail; temp=temp->next)
printf("[%d]->",(temp->value));
}
I had initially written it for single and then changed few pointers to make it circular. I am doing some mistake in it which I am not able to track and hence getting a Timeout. Please suggest.
Thanks a lot.
Upvotes: 0
Views: 1536
Reputation: 1540
This looks wrong:
tail->next=temp;
tail=temp;
tail->next=head;
temp->next=head;
It should be (if you're adding the new node at the end of the list and want it to be a circular list, like I'm assuming here):
tail->next=temp;
temp->next=head;
tail=temp;
It's a minor error, anyway: only a redundant assignment.
The really serious trouble is here:
void findcycle()
{
if (head == NULL || head->next == NULL)
printf("null");
sp=head;
fp=head->next;
while (fp != NULL && fp->next != NULL)
{
if ((fp == sp) || (fp->next == sp))
printf("Cycle");
sp = sp->next;
fp = fp->next->next;
}
printf("Not a Cycle");
}
First of all, what are you trying to accomplish? It isn't clear, so it isn't easy to suggest you how to correct it; the most obvious bug, anyway, is that if the list actually is a circular one, then the loop will go on forever, as there is no exit condition that can ever happen (no one of the pointers will ever become NULL).
Upvotes: 1
Reputation: 19971
When findcycle
finds a cycle, it doesn't exit: it just keeps going. (Likewise when it gets a list with 0 or 1 elements.) I do not guarantee that this is the only error in your code, but it suffices to make it not work.
Upvotes: 0