|
发表于 2012-2-17 23:49:54
|
显示全部楼层
本帖最后由 Mr.C 于 2012-2-18 01:25 编辑
- #include <stdio.h>
- //用于包含输入输出函数
- #include <malloc.h>
- //用于包含malloc函数
- #define LEN sizeof(struct student) //student结构大小;
- struct student *creat(); //创建链表;
- void print(struct student *head); //打印链表;
- //创建student结构体模型
- struct student
- {
- //学生ID号
- int num;
- //学生分数
- float score;
- //指向student类型的指针
- struct student *next;
- };
- int n;//全局变量,用来记录存放多少数据;
- //主函数
- void main()
- {
- //定义一个student结构体的指针变量
- struct student *stu;
- //调用create函数stu返回链表首地址
- stu = creat();
- //将首地址传给print函数,进行打印
- print(stu);
- //打印两个回车
- printf("\n\n");
- //让控制台窗口停留,以便观看输出结果
- getch();
- }
- //以下是create函数的实现过程
- struct student *creat()
- {
- //定义一个student结构体的指针变量head用来指向链表的首个地址
- struct student *head;
- //定义一个student结构体的指针的临时变量 用来传送地址
- struct student *p1, *p2;
- //将定义的指针变量初始化设置成LEN大小,这里函数名有误
- p1 = p2 = (struct student *)mall(LEN); //LEN是结构体大小;
- //打印指示
- printf("Please enter the Nun: ");
- //对学号进行赋值
- scanf("%d", &p1->num);
- //打印指示
- printf("Please enter the Score: ");
- //对分数进行赋值
- scanf("%f", &p1->score);
- //将指向链表首地址的变量初始化
- head = NULL;
- //n 用来计数的,保存学生总数
- n = 0;
- //只要学号不为0 则重复赋值
- while(p1->num)
- {
- //赋值前,学生总数加1
- n++;
- //通过学生总数来判断链表是否为空
- if(1 == n)
- {
- //如果是空,直接将正在输入的指针赋给头指针
- head = p1;
- }
- else
- {
- //从这里往下逻辑有点乱
-
-
- p2->next = p1;
- }
- //p1的值赋给p2 ,此时p1把p2又复盖了?
- p2 = p1;
- p1 = (struct student *)malloc(LEN);
- printf("Please enter the Nun: ");
- scanf("%d", &p1->num);
- printf("Please enter the Score: ");
- scanf("%f", &p1->score);
- }
- p2->next = NULL;
- return head;
- }
复制代码 |
|