data structures - Adding element to front of linked list in C -


i'm following stanford cs ed library tutorial on linked lists. trying add new list front of linked list, , it's not working based on printout length function defined below.

#include <stdio.h> #include <stdlib.h>  //build new struct node //node has value , points next node struct node{     int value;     struct node *next; };  //declare new struct node 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 function length , variable counter 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 add new lists added 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 3 element linked list named beast     struct node *beast = build123();      //add 2 elements front of linked list via pass 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 screen      printf("%d\n",len);     return 0; } 

i 3, when expect receive 5. please assist me find error in code prevents me obtaining value expect? not figure out why despite tinkering. thank you!

you don't modify headref in push function, list's head never changes. beast stays pointing original node created point to. add line:

*headref = newnode; 

in push(), , you'll set.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -