I am trying to traverse a circular singly link list in C but it’s displaying all of the elements except last one..where is the bug?
may be while condition in else part of the display function be change?but what should the condition be?
functions of display and create of link list is:
struct node
{
int data;
struct node *next;
}*last;
void create(int num)
{
struct node *t,*q;
t=(struct node*)malloc(sizeof(struct node));
t->data=num;
//list is empty
if(last==NULL){
last=t;
t->next=last;
}
else
{
t->next=last->next;
last->next=t;
last=t;
}
return;
}
void display()
{
struct node *q;
q=(struct node*)malloc(sizeof(struct node));
if(last==NULL){
printf("no items in the list");
return;
}
else{
q=last->next;
while(q!=last){
printf("%d\n",q->data);
q=q->next;
}
}
//return;
}
You start printing from
last->nextbut the condition in the while breaks whenq==last. So you are not printing thelastnode.If
elsepart is going to be executed, then you know there’s at least one node in the list. So you can change the else part to: