Insert by order in list in C

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 insert in order and I have interpreted the code several times.

For 11,1,50,7,5

Returns: 1 - > 5 - > 50

    
asked by anonymous 05.01.2019 / 18:41

1 answer

0

You're right in your comment Manuel, missing a break in your code, I've created another solution without the need for the auxiliary function and with more expressive names that makes it easier to understand.

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;
}
    
06.01.2019 / 00:04