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

标签 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;
}

这是输入和输出:

 //input
 bob 10
 shiela 5
 john 1
 elisa 10

 //print input
 elisa 10.000000
 john 1.000000
 shiela 5.000000
 bob 10.000000

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

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

最佳答案

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

p->next = head;
head = p;

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

head -> null
head -> A -> null
head -> B -> A -> null
head -> C -> B -> A -> null

等等。

然后,当您从 head 遍历到 null 时,它们看起来以相反的顺序出现,但实际上,这只是插入方法的副作用。

如果您希望它们以“正确”的顺序插入到列表中,请引入一个 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

关于c - 为什么这个链表从上次输入打印出来? C链表程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29531910/

相关文章:

c - 使用指针从一个无效函数到另一个无效函数的值?

java - 我如何从java中给定索引的链表中获取元素?

c++ - 创建链表插入功能但代码没有运行

c - "Pointer being freed not allocated error"

c - 解析字符串时,第一次迭代后第一个字母丢失

c - 从整数到字符数组的数字和打印

与结构指针一起使用的 -> 运算符是否也可以用于 union 指针?

java - 隔离链表中的偶数和奇数节点

java - java中数组名称的动态初始化?

c - 如何指示窗口过程中处理消息时出现的错误?