Insert linked list node

Asked

Viewed 71 times

0

I have this function of inserting at the beginning, but I’m not being able to test it. Follows:

void inserir_inicio (tipo_lista * p, tipo_lista * novo_no)
{
 novo_no -> prox = p;
 p = novo_no;
}

I want to identify the error of this function.

2 answers

1


tipo_lista * inserir_inicio (tipo_lista * p, tipo_lista * novo_no)
{
 novo_no -> prox = p;
 return novo_no;
}

The new_no will now be the first element, just return it. When you call the function, your list should get the function return.

Ex:

p =  tipo_lista inserir_inicio (p, novo_no);
  • It didn’t work here.

  • Was missing * in the function return type, already fixed. Now it is list_type *.

0

void inserir_inicio(tipo_lista *p, tipo_lista *novo_no){
    novo_no->prox = &(*p);
    *p = *novo_no;
}

It seems to me, you forgot to do the dereferencing pointer p. One of the ways I like to analyze function parameters is to see them as if they were implicitly declared variables within the function. For example, in your case, you wait for the address of a list-type variable to modify it using a pointer called p. But you forgot that p is a local variable of the insertir_start function, so when you say p = novo_no you are modifying the local variable, not the target variable. That’s why you dereference p and new_no: To say that you want to modify and get their memory addresses respectively.

  • And as I call it in the job?

Browser other questions tagged

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