Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding element to front of linked list in C

I'm following the Stanford CS Ed Library tutorial on Linked Lists. I am trying to add a new list to the front of my linked list, and it's not working 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 receive 5. Would you please assist me to find the error in the code that prevents me from obtaining the value I expect? I could not figure out why despite much tinkering. Thank you!

like image 614
aug2uag Avatar asked Apr 09 '13 04:04

aug2uag


People also ask

How do you insert an element at the beginning of the list?

10. How do you insert an element at the beginning of the list? Explanation: Set the 'next' pointer point to the head of the list and then make this new node as the head.


1 Answers

The problem is that when you do something like Push(&beast, 6); what beast points to is unchanged by the function Push. Even though Push adds more elements to the linked list, when you call Length on beast later it calls it on the same node that beast originally had at the start - so it is completely unknowing of the extra, added nodes.

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

*headRef = newNode;

so that beast will correctly point to the new start of the list.

like image 126
Patashu Avatar answered Nov 15 '22 10:11

Patashu