[英]Why this linked list prints from last input? C linked-list program
所以我有这个简单的链表程序:
#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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.