为什么这个链表从上次输入打印?C链表程序

XDP*_*mer 2 c linked-list

所以我有这个简单的链表程序:

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

typedef struct record record;
struct record {
    char name[32]; 
    float score;
};

typedef struct node node;
struct node {
    record data;
    node *next; 
}; 

int main() {
    char data[100];
    char name[32];
    float x;
    node *p, *head;
    int counter = 0;

    head = 0;

    while ((fgets(data, 60, stdin) != NULL) && counter <= 3) {
        p = (node *) malloc (sizeof(node));

        sscanf(data, "%s %f", name, &x);
        strcpy(p->data.name,name);
        p->data.score = x;
        p->next = head;
        head = p;

        counter++;
    }

     printf("-----------------------\n");
     while (p) {
         printf("%s %f\n",p->data.name, p->data.score);
         p = p->next ;
     }

     return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是输入和输出:

 //input
 bob 10
 shiela 5
 john 1
 elisa 10
Run Code Online (Sandbox Code Playgroud)
 //print input
 elisa 10.000000
 john 1.000000
 shiela 5.000000
 bob 10.000000
Run Code Online (Sandbox Code Playgroud)

为什么从最后一次输入开始打印?

如何从我输入的第一个数据开始打印?

pax*_*blo 6

你以相反顺序获取节点的原因是因为这段代码:

p->next = head;
head = p;
Run Code Online (Sandbox Code Playgroud)

在列表的开头插入节点,例如:

head -> null
head -> A -> null
head -> B -> A -> null
head -> C -> B -> A -> null
Run Code Online (Sandbox Code Playgroud)

等等.

然后,当你从穿越headnull,他们以相反的顺序来进行,但是,实际上,这是你的插入方法只是一个副作用.

如果您希望它们以"正确"顺序插入列表中,请引入tail指针并对其进行编码:

p->next = null;      // new node will always be end of list
if (head == NULL)    // special trap for empty list
    head = p;        //     means set up head
else                 // otherwise
    tail->next = p;  //     current tail now points to new node
tail = p;            // make new node the tail for next time
Run Code Online (Sandbox Code Playgroud)