所以我有这个简单的链表程序:
#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
为什么从最后一次输入开始打印?
如何从我输入的第一个数据开始打印?
答案 0 :(得分:6)
您以相反的顺序获取节点的原因是因为此代码:
p->next = head;
head = p;
在列表的开头处插入节点,例如:
head -> null
head -> A -> null
head -> B -> A -> null
head -> C -> B -> A -> null
等等。
然后,当您从head
遍历到null
时,他们出现以相反的顺序出现,但实际上,这只是一个方面插入方法的效果。
如果您希望将它们插入&#34中的列表中,请更正&#34;顺序,引入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