Function print circular list

Asked

Viewed 842 times

0

Personal I am with a doubt of where and how I should change to this function of printing circular list get correct.

Below is a print function from a linked list:

void imprime_lista(tipo_lista* p)
{
while (p != NULL)
{
    printf("%d\n", p->info);
    p = p -> prox;
}
printf("\n");
}

1 answer

2


Only changes that the stop criteria of the repeat loop will be when you get to the first one. It is also necessary to change the whilefor do, because the list already begins in the first element and with the while will not print anything.

void imprime_lista(tipo_lista* p)
{
    if(p==NULL)
        return;
    tipo_lista* primeiro = p;
    do
    {
        printf("%d\n", p->info);
        p = p -> prox;
    }while(p != primeiro);
    printf("\n");
}
  • It worked, but gave the message of the program stopped working, in mainI’m calling for imprime_lista(p);

  • 2

    You might want to check before you enter do {} while if primeiro is not NULL and put (p && p != primeiro) as a stop criterion; thus, if p is empty or is not a truth circular list, the function is not lost.

  • 1

    If you pass an empty list the program will give error even. I added an if to fix it. Another thing that might be causing the error is that a list that is not circular has been passed.

  • Still the same thing

  • 1

    Probably your circular list is wrong at some point

  • Take a look please: https://pastebin.com/9VKC7uBK

  • 1

    The insert function is wrong, it is inserting as a simple list and not as circular, so after the last element the list goes to NULL and is where the error happens.

  • @Lucigueiro I changed the insert function, the current code is like this: [coddigocomplete]: https://pastebin.com/GBd9xjCH Now I do not know where the error is happening if it is in the print or insert function. If you run nothing comes out on the screen. Thanks.

  • The error is in the inserts because you check if it is null and returns and as the list starts in null the program will never get out of it.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.