Delete a value from a node

1

I'm trying to delete a data from my list but it turns out that the next value of the number I want to delete is deleted.

For example, I have on my list:

7 0 5 18 2 

I want to delete the 0 , and that when viewing is:

7 5 18 2

With the code that I have, it looks like this:

7 0 18 2 

The following value of 0 is erased, that is, 5 .

Code:

printf("\n\nNumero de la lista a borrar: ");//Valor del nodo a borrar
scanf("%d",&numeroABorrar);

anterior = primero;
while ((anterior->dato != numeroABorrar) && (anterior != NULL))
{
    anterior = anterior->siguiente;
}       

if (anterior != NULL)
{   
    aux = anterior->siguiente;  
    anterior->siguiente = aux->siguiente;
    free(aux);      
}   
    
asked by Mario Guiber 08.08.2017 в 23:41
source

1 answer

2

It seems to me that having a match the variable that contains the value to be deleted is previous but the reassignment that you do is that the next previous (the one you want to delete) is the next to the next one you want to delete , so you lose the reference to the one you want to delete from . Let's say you're going through a value. I hope that the following example is clearer.

Applying it to the list:

Previous is 0

At aux this is 5

The next one from 0 (from previous) is now 18, the reference to 5 has already been lost

To correct this you need a reference to the predecessor of the value you want to delete (7) and the next one of that value assign the next one you want to delete (change the reference to 0 by the reference to 5):

printf("\n\nNumero de la lista a borrar: ");//Valor del nodo a borrar
scanf("%d",&numeroABorrar);

actual = primero;
while ((actual->dato != numeroABorrar) && (actual != NULL))
{   
    anterior = actual;
    actual = actual->siguiente;
}       

if (actual != NULL)
{   
    //codigo que verifica el caso de que el elemento a borrar
    //sea el primero
    if(actual == primero){
        primero = primero->siguiente;
    }
    else{
        anterior->siguiente = actual->siguiente;
    }                 
}   

Note that the aux variable is no longer necessary and that before passing to the next one in the while loop, I save a reference to it in previous to be able to change its next

    
answered by 08.08.2017 / 23:56
source