Linked list add new root element

Viewed 155

I'm trying to add a new root element to my linked list. I already know the correct answer but I dont understand why there's a double pointer to the current root element. Here's the correct code:

void elementAsRoot(Element **oldRoot, Element *newRoot){
  newRoot -> next = *oldRoot;
  *oldRoot = newRoot;
}
3 Answers

I am pretty sure you could just remove the double pointer since you are, in the end, dereferencing the double pointer.

void elementAsRoot(Element *oldRoot, Element *newRoot) {
  newRoot->next = oldRoot;
  oldRoot = newRoot;
}

I answer you by commenting. Here is what happens inside elementAsRoot.

oldRoot is a pointer to the location/address of the variable that keeps the root of the list in the calling function. You want to mutate this root inside the elementAsRoot and this is why you pass the address of a pointer.

void elementAsRoot(Element **oldRoot, Element *newRoot){

first you initialize newRoot to point to the old root

  newRoot -> next = *oldRoot;

next, you mutate the old root (defined externally to this function) to point to the new added node.

  *oldRoot = newRoot;

}

The calling function looks something like

Element *root, *newroot;
....  
newroot = malloc(sizeof Element);
// here your list look like root=A => rest .
// This call will mutate root to be new.
elementAsRoot(&root, new);
// here your list look like root=new => A => rest
void elementAsRoot(Element **oldRoot, Element *newRoot){
  newRoot -> next = *oldRoot;
  *oldRoot = newRoot;
}

This function is meant to be called like so:

Element *list = ...some linked list...;
elementAsRoot(&list, ...some new element...);
// now 'list' points to the new first element, not the old one (which is now second)

To update a variable from the caller, the function needs a pointer to the variable. If the first parameter was just list, not &list, then the function would not be able to update the value of list and so it wouldn't be able to do its job.

Related