这是我的 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/