Add item to top of linked list in C

I follow the Stan Library CS Ed Library tutorial on linked lists. I am trying to add a new list to the top of the linked list and it does not work based on the printout I get from the Length function defined below.

#include <stdio.h> #include <stdlib.h> //build new struct for node //node has value and points to next node struct node{ int value; struct node *next; }; //declare a new struct node that contains 3 nodes (head, middle, tail) struct node *Build123(){ struct node *head, *middle, *tail = NULL; head = malloc(sizeof(struct node)); middle = malloc(sizeof(struct node)); tail = malloc(sizeof(struct node)); head->value = 3; head->next = middle; middle->value = 5; middle->next = tail; tail->value = 9; tail->next = NULL; return head; }; //declare a function Length and variable counter to calculate size of list int Length(struct node *head) { int count = 0; struct node *iterator = head; while (iterator != NULL) { count++; iterator = iterator->next; } return count; } //declare function Push to add new lists that would be added to the front void Push (struct node **headRef, int value){ struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->value = value; newNode->next = *headRef; } int main(){ //instantiate the 3 element linked list named beast struct node *beast = Build123(); //add 2 elements to the front of the linked list via pass by reference Push(&beast, 6); Push(&beast, 12); //calculate length of linked list after elements have been added int len = Length(beast); //print length of linked list to screen printf("%d\n",len); return 0; } 

I get 3 when I expect to get 5 . Could you help me find an error in the code that prevents me from getting the value that I expect? I could not understand why, in spite of a lot of messing around. Thanks!

+6
source share
3 answers

You do not change headRef in your Push function, so your list never changes. beast always points to the source node that was created to indicate. Add this line:

 *headRef = newNode; 

In Push() , and you will be installed.

+3
source

The problem is that when you do something like Push(&beast, 6); , what beast indicates is not changed by the Push function. Despite the fact that Push adds more elements to the linked list, when you call Length on beast later, it calls it on the same node that the beast originally had at the beginning, so that it does not completely know the additional nodes added.

At the end of Push () you need to do the following:

*headRef = newNode;

so that beast correctly points to a new start to the list.

+4
source

At the end of the push() method, you should add:

*headRef = newNode

This is because headRef should always point to the first node in your linked list.

+1
source

All Articles