Linked list

I have a linked list that looks like this [10]-[20]-[30]-[35]-[40]
I call out function insertFront(&head,5); which inserts a node to the front of the list. I'm drawing a blank here on how this inserts to the front. Address of head is the address of [10], so doesn't **head point to [30] and *head point to [20]. So how do you get to the front. Pleas explain what is going on here.

void insertFront(struct Node **head, int n) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = *head;
*head = newNode;
Last edited on
You should reread the pointers and dereferencing them.

Your calling function apparently has a (I do rename here to simplify) Node *listHead. listHead points to a Node. You call insertFront( &listHead, 5 ).

head points to the variable listHead of the caller. The type of *head is Node *. That pointer points to a Node. *head = newNode; modifies listHead so that it now points to the new head node.

The type of **head is Node. The struct value that the *head has address of.

In other words, when entering the insertFront:
  head == &listHead
 *head == listHead
**head == *listHead
*head->data == 10
*head->next->data == 20
*head->next->next->data == 30
Last edited on
Thanks very much.
Topic archived. No new replies allowed.