c - 在单链表的开头插入节点

标签 c linked-list singly-linked-list

我的 add_to_list 函数在这里有问题。

我正在使用此函数将节点添加到列表指针引用的单链表的开头。

问题是:第一个节点被添加,如果我再添加更多,我就失去了列表的踪迹。

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

struct node {
    int value;
    struct node* next;
};

struct node *add_to_list(struct node *list , int n){
     struct node *new_node ;
     new_node = malloc( sizeof(struct node) ); //create new node
     if(new_node == NULL){
         printf("Error ,malloc failed to allocate memory\n");
         exit(EXIT_FAILURE);
     }
     new_node->value = n; //initiate value field
     new_node->next = list;
     return new_node;
}

int main(){
    struct node * first = NULL;
    struct node * temp = first;
    first = add_to_list(first,10);
    if(first != NULL)
        printf("node added\n");
    else
        printf("add failed\n");
    first = add_to_list(first,20);
    if(first == NULL)
        printf("node added\n");
    else
        printf("add failed\n");
    first = add_to_list(first,30);
    if(first == NULL)
        printf("node added\n");
    else
        printf("add failed\n");

    while(temp!=NULL){
        printf("%d-->",(temp->value));
        temp = temp ->next;
    }

    return 0;
}

最佳答案

所以在 main 的开头你有这两行...

struct node * first = NULL;
struct node * temp = first;

...将 NULL 分配给 first 然后将 first 的值分配给 temp 这意味着两者其中有 NULL。这是一次性分配 - temp 不会随着 first 的更改而更新。

当您到达函数的底部时,您会遇到此循环,但自从第一次分配 NULL 以来,没有任何内容更新 temp 的值。

while(temp!=NULL){
    printf("%d-->",(temp->value));
    temp = temp ->next;
}

解决方案是在循环之前将 first 的当前值分配给 temp,如下所示:

temp = first;
while(temp!=NULL){
    printf("%d-->",(temp->value));
    temp = temp ->next;
}

关于c - 在单链表的开头插入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46913168/

相关文章:

C++ 链表不保留新节点

C 链表在末尾添加项

可变长度的字符

c - Azure Sphere 不向物联网中心发送遥测数据 IOTHUB_CLIENT_CONNECTION_NO_NETWORK

c - C 中未读取整个文件(意外出现 EOF)

使用队列和链表的 Groovy 示例应用程序

c - 如何克隆具有头/尾实现的链表?

c - 为什么 C 程序使用 libmath 的 .so 比使用 libmath 的 .a 显示更多的内存?

c++ - 为什么我的列表上的迭代失败?

c - 递归地在链表末尾插入节点