c - 插入到链表的开头(重新访问)

标签 c pointers linked-list printf insertion

我对用 C 编写代码非常陌生(因此我正在做这个愚蠢的练习)。我试着看这个 other solution类似的问题,但似乎我的编码策略不同,最终我想了解我的代码有什么问题。非常感谢您的意见。

我有一个链表、一个在列表开头插入新节点的函数、一个打印链表的函数和 main 函数。

不幸的是,我对 C 的了解还不足以理解为什么我的函数没有插入到列表的开头。更不幸的是这段代码并没有崩溃。

#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);

}

这段代码只会打印我试图添加到列表中的最后一个节点,因此会覆盖之前的节点。

例如:

Running…
15 

Debugger stopped.
Program exited with status value:0.

最佳答案

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

检查 working code


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

因为在 main 中您创建了三个临时节点并将每个节点的 next 初始化为 NULL,包括 list 节点所以在 add_to_list() 函数中 if condition (( *list)->next == NULL) 始终评估为 true 并且 list 始终使用临时节点进行初始化。

关于c - 插入到链表的开头(重新访问),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19543924/

相关文章:

c++ - 什么时候关闭 __STRICT_ANSI__ 标志是不安全的?

c - 如何做一个矩阵指针数组?

c - 通过文本文件读入并显示链表

c - C中如何指向当前节点的上一个节点和当前节点的下一个节点?

C:如何在我的代码中打破这个循环?

c - 选择维度以在 C 中使用 FFTW 执行 FFT

c++ - 如何在CPP中删除动态非矩形二维数组

对C中返回指针时的安全问题感到困惑

c# - 什么时候应该使用链接列表的真实世界示例是什么?

c - 段错误(核心转储)问题