我正在尝试实现链接列表。我对这段代码有疑问。说,我想创建一个应该有3个项目的列表,项目是45,56,67。我得到的输出是0,45,56。有什么问题?
#include <stdio.h>
#include <stdlib.h>
void add(int b);
void display();
struct node
{
int data;
struct node *next;
}*head, *ptr;
int main()
{
int a,b;
int i = 0;
head = malloc(sizeof(struct node));
printf("enter the number of entries:\n");
scanf("%d",&a);
while(i<a)
{
printf("enter the value:\n");
scanf("%d", &b);
add(b);
display();
i++;
}
return 0;
}
void display()
{
struct node *list = head;
while(list->next != 0)
{
printf("%d -> ",list->data);
list = list->next;
}
}
void add(int b)
{
struct node *p = head;
struct node *ptr = (struct node*)malloc(sizeof(struct node));
ptr->data = b;
ptr->next = 0;
while(p->next!=0)
{
p = p->next;
}
p->next = ptr;
}
答案 0 :(得分:0)
完成添加后,请尝试在单独的循环中调用display()
答案 1 :(得分:0)
at main
head = malloc(sizeof(struct node));
head->next = NULL;//necessary to set to NULL
显示
printf("%d -> ", list->next->data);//The top node is not used