Insert in list order in C

Asked

Viewed 147 times

0

I have the following function:

Nodo * insertOrder(Nodo *L,Nodo *nv){
  //11,1,50,7,5
  if(L==NULL){
    return nv;
  }
  if(nv->id < L->id){
    return (insertFirst(L, nv));
  }
  int c=0;
  Nodo *aux2=L;
  Nodo *aux=NULL;
  while(L!=NULL){

    if(nv->id < L->id){
      c=1;
      aux->nseg=nv;
      nv->nant=aux;
      L->nant=nv;
      nv->nseg=L;
    }
    aux=L;//guarda o elemento anterior
    L=L->nseg;
  }
  if(c==0){
    aux->nseg=nv;
    nv->nant=aux;
  }
  return aux2;
}

I do not understand why the function mentioned does not enter in order and I have interpreted the code several times.

For 11,1,50,7,5

Return: 1 -> 5 -> 50

  • 1

    Missing a break; inside the while cycle if

  • "For 11,1,50,7,5 " - what does each of these values mean ? " Returns: 1 -> 5 -> 50" - and what was supposed to return ? What are the two function parameters insertOrder ? How the structure was defined Nodo and their typedefs ?

  • the arrow is the pointer to the next element:1->5->7->11->50. Only one break was missing inside the if. I already solved the problem

  • If you have already solved the problem the ideal is to put the solution as a properly detailed answer so that a person with a similar problem can also solve it.

1 answer

0


You are right in your comment Manuel, missing a break in your code, I created another solution without the need for the auxiliary function and with more expressive names that facilitate understanding.

Nodo * inserirListaOrdem(Nodo *inicio, Nodo *novo)
{
    if(inicio == NULL)
    {
        return novo;
    }

    Nodo *p = inicio;
    Nodo *anterior = NULL;

    /*search position for insertion*/
    while(p != NULL && p->conteudo < novo->conteudo)
    {
        anterior = p;
        p = p->proximo;
    }
    /*insere elemento*/
    if(p->proximo == NULL)
    {
        p->proximo = novo;
        novo->proximo = NULL;
    }
    else
    {
        anterior->proximo = novo;
        novo->proximo = p;
    }
    return inicio;
}

Browser other questions tagged

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