c语言:写一个函数建立一个有3名学生数据的单向动态链表
2016-03-12 17:05
519 查看
写一个函数建立一个有3名学生数据的单向动态链表。
解:程序:
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Student)
struct Student
{
long num;
float score;
struct Student *next;
};
int n;
struct Student *creat(void)//定义函数返回一个指向链表头的指针
{
struct Student *head;
struct Student *p1, *p2;
n = 0;
p1 = p2 = (struct Student *)malloc(LEN);
scanf("%ld,%f", &p1->num, &p1->score);
head = NULL;
while (p1->num!=0)
{
n = n + 1;
if (n == 1)
{
head = p1;
}
else
{
p2->next = 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();//函数返回链表第1个结点的地址
printf("\nnum=%ld\nscore=%5.1f\n", pt->num, pt->score);//输出第1个结点的成员值
return 0;
}
结果:
1001,67
1003,89
1005,99
0,0
num=1001
score= 67.0
请按任意键继续. . .
本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1750276
解:程序:
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Student)
struct Student
{
long num;
float score;
struct Student *next;
};
int n;
struct Student *creat(void)//定义函数返回一个指向链表头的指针
{
struct Student *head;
struct Student *p1, *p2;
n = 0;
p1 = p2 = (struct Student *)malloc(LEN);
scanf("%ld,%f", &p1->num, &p1->score);
head = NULL;
while (p1->num!=0)
{
n = n + 1;
if (n == 1)
{
head = p1;
}
else
{
p2->next = 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();//函数返回链表第1个结点的地址
printf("\nnum=%ld\nscore=%5.1f\n", pt->num, pt->score);//输出第1个结点的成员值
return 0;
}
结果:
1001,67
1003,89
1005,99
0,0
num=1001
score= 67.0
请按任意键继续. . .
本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1750276
相关文章推荐
- c语言之位域 -- 减少变量空间的有效利器
- c语言:建立简单的静态链表,它由3个学生数据的结点组成,要求输出各结点的数据
- C++读写二进制文件
- VC++2005 使用调用webserver ,使用MSXML读取XML文件
- 《你必须知道的495个C语言问题》读书笔记之第8-10章:字符串、布尔类型和预处理器
- 软件工程课程作业(二)--四则运算2改进版(c++)
- HDOJ 1087Super Jumping! Jumping! Jumping!解题报告
- C语言实现四则运算
- VC++程序开机自动启动
- STL 容器特点简单总结
- 编写C++程序使DirectShow进行视频捕捉
- 链表(list)的实现(c语言)
- C++ Primer 5th - 1.1 编写一个简单的C++程序
- C/C++基础知识(一)数组和指针
- (各个公司面试原题)在线做了一套CC++综合測试题,也来測一下你的水平吧(二)
- C++第1-1次上机实验
- C语言中a=b=c,a=b==c,a==(b=c),a==(b==c)的简单分析
- 详解C++循环创建多级目录及判断目录是否存在的方法
- C++第一次实验—2
- C++ auto类型说明符