1

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.
4

1 回答 1

1

功能上的一个错误add_to_list()

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

应该只是:

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

检查工作代码


为什么你只得到15最后一个节点 ( temp3) 值?

因为在 main 中,您创建了三个临时节点并将每个节点的 next 初始化为 NULL,如果条件 始终评估为 true 并始终使用临时节点初始化,则list在函数中包括 node so 。add_to_list()((*list)->next == NULL)list

于 2013-10-23T14:14:57.657 回答