|
发表于 2013-10-4 14:03:01
|
显示全部楼层
- #include "stdio.h"//包含三个头文件
- #include "malloc.h"
- #include "stdlib.h"
- #define LEN sizeof(struct student)//宏定义 LEN 为 sizeof(struct student)
- struct student *creat();//creat函数前置声明
- void print (struct student *head);//print函数前置声明
- struct student//定义类型
- {
- int num;
- float score;
- struct student *next;
- };
- int n;//定义全局变量
- void main()
- {
- struct student *stu;//定义存放student类型的指针
- stu = creat(); //stu = 链表的头指针
- print(stu); //用print函数输出链表
- printf("\n\n");//两换行符
- system("pause");//中断
- }
- struct student *creat()
- {
- struct student *head;//定义存放student类型的指针
- struct student *p1,*p2;
- p1=p2=(struct student *)malloc(LEN);//把p1 p2 都指向malloc所分配的动态内存的地址
- printf("please enter the num:");//接受输入
- scanf("%d",&p1->num);
- printf("please enter the score:");
- scanf("%f",&p1->score);
- head = NULL;//头指针指向空 也就是说这是个空链表
- n=0;//讲全局变量赋值成0
- while (p1->num)//只要p1->num 不等于0 就执行循环 也就是说上面的接受输入处 看你输入的num 是不是0
- //不是0就执行循环
- {
- n++;//n = n + 1 计算有多少组数据
- if(1==n)//如果 n == 1 也就是说是第一次输入 之前那次如果输入不是0 进入循环的话那次也是算的
- //数据在那时候已经存入 n++ 得到现在有一组数据了
- {
- head = p1; //让头指针指向我们动态分配的地址 为什么不用我说了吧除非你连链表是什么
- //都不知道
- }
- else //如果不是第一次输入
- {
- p2->next=p1;//头指针当然不能变了 变得就是next这个指针 原因 也不多说了 除非你不知道什么
- //是链表
- }
- p2=p1;//赋值语句不解释
- p1=(struct student *)malloc(LEN);//再次动态分配内存 接受输入 继续判断是否进入循环
- printf("please enter the num:");
- scanf("%d",&p1->num);
- printf("please enter the score:");
- scanf("%f",&p1->score);
- }
- p2->next=NULL;//结束后 应为p1->next指向的是那个输入num是0的内存 但由于不在进入循环 p2->
- //next并没有指向那块内存而是指向了最后一块输入num不是0的内存是正确的 把p2->
- //next 指向NULL 这样链表就完成了
- return head;//把头指针返回即可 获得整条链表的数据
- }
- void print(struct student *head)
- {
- struct student *p;
- printf("\nthere are %d records!\n\n",n);//输出有多少个数据 用全局变量n计算
- p=head;
- if (head)//只要head不是NULL 也就是说不是空链表
- {
- do
- {
- printf("学号为%d的成绩是:%f\n",p->num,p->score);//输出p指向数据 第一次就是头指针指向的
- //之后 p=p->next;//把p指向下一个数据
- p=p->next;//把p指向下一个数据
- }while (p);//只要p 不是NULL 就是说只要不是最后一个数据就继续循环输出
- }
- }
复制代码 |
|