Function remove start List

1

Personal I have this remove function at the beginning, it happens that when I enter numbers such as: 1 2 3, and then I call the remove function at the beginning and delete the number 2, while the correct was to delete the number 1 , because it is the beginning of the list. Have tried everything here, to my limit and I could not.

int retira_no_inicio (tipo_lista *p)
{
tipo_lista * aux;
//tipo_lista * ant;

if (p -> prox == NULL)
{
    return NULL;
}

aux = p -> prox;
p -> prox = aux -> prox;
return p;
}
    
asked by anonymous 26.04.2017 / 15:55

1 answer

1

Let's say that the list consists of three values: 1, 2, and 3. The p pointer points to the beginning of the list:

+---+    +---+    +---+
| 1 | -> | 2 | -> | 3 |
+---+    +---+    +---+
  ^
  p

It is checked if p->prox is NULL , false, so the aux pointer will receive p->prox :

+---+    +---+    +---+
| 1 | -> | 2 | -> | 3 |
+---+    +---+    +---+
  ^        ^
  p       aux

And p->prox gets aux->prox :

       +-------+ 
+---+  | +---+ |  +---+
| 1 | -+ | 2 | +> | 3 |
+---+    +---+    +---+
  ^        ^
  p       aux

Returning p . So the final list is:

+---+    +---+
| 1 | -> | 3 |
+---+    +---+
  ^
  p

To fix, just return the reference of aux , because the list will start at 2, eliminating the value 1. It is good to remember that since you are using dynamic allocation (#

tipo_lista* retira_no_inicio(tipo_lista *p) { tipo_lista *aux = p->prox; free(p); return aux; }

  

Note : Note that the function return MUST be of type tipo_lista and not int .

    
26.04.2017 / 16:20