Question

I'm very new to coding in C (and therefore the silly exercise I am working on). I tried looking at this other solution to a similar question, but it seems like my coding strategy is different, and ultimately I would like to understand what is the problem with my code. I would greatly appreciate your input.

I have a linked list, a function that inserts a new node at the beginning of my list, a function that prints my linked list, and main function.

Unfortunately my knowledge of C is not good enough to understand why my function is not inserting at the beginning of the list. What is even more unfortunate is that this code does not crash.

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* next;
} *Node_t;

void print_list(Node_t root) {
    while (root) {
        printf("%d ", root->data);
        root = root->next;
    }
    printf("\n");
}

void add_to_list(Node_t *list, Node_t temp){
    // check if list is empty
    if ((*list)->next == NULL) {
        // insert first element
        (*list) = temp;
    }
    else {
        temp->next = (*list);
        (*list) = temp;
    }
}

int main () {

    int val1 = 4;
    int val2 = 8;
    int val3 = 15;

    Node_t list = malloc(sizeof(struct Node));
    Node_t temp1 = malloc(sizeof(struct Node));
    Node_t temp2 = malloc(sizeof(struct Node));
    Node_t temp3 = malloc(sizeof(struct Node));

    temp1->data = val1;
    temp1->next = NULL;
    temp2->data = val2;
    temp2->next = NULL; 
    temp3->data = val3;
    temp3->next = NULL; 

    //Initialize list with some values
    list->data = 0;
    list->next = NULL;

    /* add values to list */
    add_to_list(&list,temp1);
    add_to_list(&list,temp2);
    add_to_list(&list,temp3);

    print_list(list);

}

This code will only ever print the last node I have attempted to add to the list, therefore overwriting the previous nodes.

For example:

Running…
15 

Debugger stopped.
Program exited with status value:0.
Était-ce utile?

La solution

A single mistake in add_to_list() function:

if ((*list)->next == NULL) { // checks next of first is NULL not list is NULL
 // to insert at first 

should be just:

if ((*list) == NULL){ // You need to check list is NULL

Check working code


Why you were getting only 15 the last node (temp3) value?

Because in main you creates three temp nodes and initialized next of every node to NULL, including list node so in add_to_list() function if condition ((*list)->next == NULL) always evaluates true and list always initialized with temp node.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top