Inserting in circular list

Asked

Viewed 1,321 times

-1

I am having doubts in this code of the function of inserting circular list.

tipo_lista * inserir_inicio (tipo_lista * p, tipo_lista * novo_no)
{
 //Se a lista estiver vazia
 if(p==NULL)
     return novo_no;

 tipo_lista* r = p; //Para manter a referencia ao primeiro elemento
 while (p->prox != NULL)
 {
     p = p->prox;
 }
 p->prox = novo_no;
 return r;
}

It’s not working properly and I’m wondering if it’s on that line of NULL.

  • 1

    This list is not circular. A circular list has no end; let’s say the last element points to the first, not null

  • 1

    Do you talk about a double-linked or circular list? If it is actually circular, the while is an infinite loop, because there will always be a next. On this site ( >https://www.tutorialspoint.com/data_structures_algorithms/circular_linked_list_algorithm.htm ), a circular list is defined as having a head, which makes it possible to insert it at the beginning. In the link there is an example of insertion.

  • 1

    You say: novo -> prox = novo;?

  • @Filipeolegario circular only.

  • @Lucastrigueiro please give an answer on this. I am not able to function the list on, nor print, nor insert, based on the main that you had done, only missing those two functions.

  • 1

    First need to know in which position you are trying to insert, start? order? ordered?

  • insert normally start, 1,2,3

Show 2 more comments

1 answer

2


If the list should be circular only, there is no start and no end. In this case, add the new no anywhere. The following code adds you between the past as parameter and its successor.

void inserir_inicio (tipo_lista * p, tipo_lista * novo_no)
{
 //Se a lista estiver vazia
 if(p==NULL)
     return;

 novo_no->prox = p->prox;
 p->prox = novo_no;
}

As I did not see reference to an earlier element, I assume that the list is not double-linked.

  • 1

    Compiled without error, but nothing appears on the screen.

  • 1

    How is the printing function to be able to print on the screen?

  • Do you want to print a node field? Example, your list_type would be defined like this(?): struct list_type_list *Prox; int key; }

  • if it is, Voce can make printf("%d", p->key).

Browser other questions tagged

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