输出链表数据时,只能输出前两项。

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

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

void add(struct node** head,int n);
void display(struct node* head);

int main()
{
struct node* head=malloc(sizeof(struct node));

int n=0;
while(1)
{
    puts("Enter a number to linklist:");
    scanf("%d",&n);
    add(&head,n);
    if(n==-1)
        break;
}
display(head);
return 0;

}

void add(struct node** head,int n)
{
if(n==-1)
{
puts("Input error,next display linklist\n");
}
else
{
struct node* new_node=malloc(sizeof(struct node));
new_node->a=n;
new_node->next=*head;
(*head) ->next=NULL;
*head=new_node;
printf("%zd\n",new_node);
printf("%zd\n",new_node->next);
}
}

void display(struct node* head)
{
struct node* temp=head;
while(temp)
{
printf("%zd\n",temp);
printf("%d\n",temp->a);
temp=temp->next;
}
}

修改处见注释,供参考:

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int a;
    struct node* next;
};

void add(struct node** head, int n);
void display(struct node* head);

int main()
{
    struct node* head = NULL;  //= malloc(sizeof(struct node)); 修改
    int n = 0;
    while (1)
    {
        puts("Enter a number to linklist:");
        scanf("%d", &n);
        if (n == -1)        //修改
            break;
        add(&head, n);
    }
    display(head);
    return 0;
}

void add(struct node** head, int n)
{
    if (n == -1)
    {
        puts("Input error,next display linklist\n");
    }
    else
    {
        struct node* new_node = (struct node*)malloc(sizeof(struct node)); //修改
        //struct node* new_node = malloc(sizeof(struct node));
        new_node->a = n;
        new_node->next = *head;
        //(*head)->next = NULL;  修改
        *head = new_node;
        printf("%zd\n", new_node);
        printf("%zd\n", new_node->next);
    }
}

void display(struct node* head)
{
    struct node* temp = head;
    while (temp)
    {
        printf("%zd\n", temp);
        printf("%d\n", temp->a);
        temp = temp->next;
    }
}

上面的代码应该够用了,错误原因是 (*head)->next = NULL; 你每次创建新的节点之后都让原来的head的next指空,那么head加上新节点,永远只会有两个节点