Function remove Start List

Asked

Viewed 327 times

1

I am with this function to remove at the beginning, it happens that when I insert numbers as for example: 1 2 3, and then call the function to remove at the beginning and delete the number 2, while the correct one was to delete the number 1, because it is the beginning of the list. Already try everything here, up 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;
}

1 answer

1


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

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

It is verified whether p->prox is NULL, false, therefore, the pointer aux will receive p->prox:

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

And p->prox receives aux->prox:

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

Returning p. So the final list is:

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

To correct, just return the reference of aux, as the list will start at 2, eliminating the value 1. It is good to remember that as you are using dynamic allocation (source), you need to free the memory from the removed node:

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

    free(p);

    return aux;
}

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

  • 2

    According to the last questions you asked here in the community, which are ALL related to the same problem, I strongly recommend you go back to basics and study the concepts again. If it was really you who made these codes, you shouldn’t have so many difficulties in designing these functions. Take your books again and review your codes. It will be much more profitable for you.

  • It’s not really my codes, I’m studying this in college and I don’t have any experience, I’m at the beginning of the semester, I’m having some free time and I want to test to see if you’re certain those functions that were passed on, some I got to test and some I ask for help in the forum, I only ask for help after trying several times. But very grateful for the tip.

  • 2

    If you have free time, forget the codes ready and try to do them yourself.

  • I have a lot of difficulty programming, but this explanation your there was excellent saw, I’m doing table test and I understood right.

  • I made a function remove_no_fim with type int and it worked.

Browser other questions tagged

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