本题要求实现一个将输入的学生成绩组织成单向链表的简单函数。
函数接口定义:
void input();
该函数利用scanf从输入中获取学生的信息,并将其组织成单向链表。链表节点结构定义如下:
struct stud_node {
int num; /*学号*/
char name[20]; /*姓名*/
int score; /*成绩*/
struct stud_node *next; /*指向下个结点的指针*/
};
单向链表的头尾指针保存在全局变量head和tail中。
输入为若干个学生的信息(学号、姓名、成绩),当输入学号为0时结束。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stud_node {
int num;
char name[20];
int score;
struct stud_node *next; }; struct stud_node *head, *tail;
void input();
int main() {
struct stud_node *p;
head = tail = NULL;
input();
for (p = head; p != NULL; p = p->next)
printf("%d %s %d\n", p->num, p->name, p->score);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
1 zhang 78
2 wang 80
3 li 75
4 zhao 85
0
输出样例:
1 zhang 78
2 wang 80
3 li 75
4 zhao 85
思路:创建个临时节点指针 *temnode,其指向的空间用来存储每次输入的数据。对于第一组数据,head 和 tail 同时指向其存储空间,即 head = tail = temnode;对之后的数据 head 不再变化, tail 的下级指针指向数据存储空间 ,即 tail -> next = temnode,然后 tail 指针移位, tail = tail —>next。
注意:临时节点指针的创建有固定套路:
struct stud_node temnode = (struct stud_node)malloc(sizeof(struct stud_node));
代码:
void input() {
int tem = 0;
int thenum;
while (scanf("%d",&thenum)&&thenum){
struct stud_node *temnode = (struct stud_node*)malloc(sizeof(struct stud_node));
temnode->num = thenum;
scanf("%s %d", temnode->name, &temnode->score);
if (tem == 0) {
tem = 1;
tail = head = temnode;
}
else {
tail->next = temnode;
tail = tail->next;
}
}
}
之前的错误思路:head 和 tail 同时指向一片新的存储空间,即
tail = head = (struct stud_node*)malloc(sizeof(struct stud_node));
每次输入的数据,存储到 tail 指向的空间,
再令 tail 的下级指针指向一片新的存储空间,tail 指针移位, tail = tail->next;
所有数据输入完毕,此时 tail 指向的空间没有存储数据,所以 delete tail,tail =NULL;但问题是 delete 并非真正删除 tail ,tail 会随机指向一个空间,直到程序完全结束,
所以没有数据的 tail !=NULL,输出时,会多输出一行 0 0。
代码:
void input() {
tail = head = new stud_node();
while (scanf("%d", &tail->num) && tail->num) {
scanf("%s %d", tail->name, &tail->score);
tail->next = new stud_node();
tail = tail->next;
}
delete tail;
tail = NULL;
}
(研究了一下午,终于整明白了!o( ̄▽ ̄)ブ)