我正试图实现一个链表。我对这段代码有一个问题。比如说,我想创建一个有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;
}
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
尝试在添加完成后在单独的循环中调用display()