Pergunta

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;
}
Foi útil?

Solução

You start printing from last->next but the condition in the while breaks when q==last. So you are not printing the last node.

If else part 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:

q=last->next;
do{
    printf("%d\n",q->data);
    q=q->next;
}while(q!=last->next);

Outras dicas

last is also a valid note in this case, and the way you are breaking out of the loop is fine. You should just add a little code after the while loop to print the last node too.

You are not printing the last node of the circular list.

Add

printf("%d\n",q->data);

after the else block in display()

Or instead of putting an ugly printf after else block, you can consider using do while construct .

And you need not do memory allocation for q in display(). Just

struct node *q;

must be enough. since you are holding only the pointer to traverse the list.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top