c - 链接列表元素未显示

标签 c pointers data-structures struct linked-list

这是我的 C 程序,它总是在末尾插入一个链表。但是当我尝试打印列表元素时,什么也没有显示。这是代码:

#include<stdio.h>
#include<stdlib.h>
struct Node
{
    int data;
    struct Node *next;
};
void insert(struct Node *, int);
int main(void)
{
    struct Node *head = NULL, *current;
    int n, i, x, data;
    scanf("%d", &n);
    for(i = 0; i < n; i++)
    {
        scanf("%d", &data);
        insert(head, data);
    }
    current = head;
    while(current != NULL)
    {
        printf("%d ", current->data);
        current = current->next;
    }
}
void insert(struct Node *head, int data)
{
    struct Node *newnode, *current = head;
    newnode = (struct Node *)malloc(sizeof(struct Node));
    newnode->data = data;
    newnode->next = NULL;
    if(head == NULL)
    {
        head = newnode;
    }
    else
    {
        while(current->next != NULL)
        {
            current = current->next;
        }
        current->next = newnode;
    }
}

我不明白可能是什么问题。请帮忙。

最佳答案

您的insert 不能修改head。改成

void insert(struct Node **head, int data)

并改变它

*head = newnode;

然后这样调用它

insert(&head, data);

关于c - 链接列表元素未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45364875/

相关文章:

python - 将 ctypes 结构传递给 cython

algorithm - 字符串的有效排列

python - 实现一个带约束的 python 列表

Python数据结构设计

c++ - 在 MPI-IO 上交织来自不同处理器的二进制数据

c - 如何将 C 代码编译成 Swift Framework

从头文件调用 Struct 到 main 函数

c# - c# 编译器是否在编译期间解析引用的引用?

c - 为什么 strlen 的参数是 "const"?

c - 双指针取消引用时的内核错误