动态链表的建立与输出
C语言程序设计(第五版)谭浩强
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <stddef.h>
# define LEN 1 * sizeof(struct Student)
int n = 0; //全局变量n;
struct Student {
long num;
float score;
struct Student *next; //next存放下一个结点地址
};
struct Student *creat(void) {
struct Student *head = NULL; //head是头指针
struct Student *p1, *p2;
n = 0;
p1 = p2 = (struct Student *) malloc(LEN); //开辟一个结点 , 且令指针p1, p2指向该单元格 ;
scanf("%ld,%f", &p1->num, &p2->score); //输入第一个学生数据
while (p1->num) { // 第一个学生成绩不为0时 ,函数出口;
if (++n == 1) head = p1;//使头指针指向第一个结点
else p2->next = p1; //使结点next指针存放p1的地址
p2 = p1; //使p2与p1指向同一个结点
p1 = (struct Student *) malloc(LEN); //开辟新的结点
scanf("%ld, %f", &p1->num, &p1->score); //输入数据
}
p2->next = NULL;
return head;
}
int main() {
struct Student *pt;
pt = creat();
while (pt) {//输出链表
printf("%\nStudent.num:%ld\nStudent.score:%5.1f\n", pt->num, pt->score);
pt = pt->next;
}
return 0;
};