|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(Stu) //宏替换 LEN代表struct student
//类型数据的长度 sizeof是 求字节数运算符
typedef struct Student
{
long num;
float score;
struct Student* next;
}Stu;
int n; //n为全局变量,本文件中各模块均可使用它
Stu* creat(void) //定义结构函数,此函数返回一个指向 链表头的指针
{
Stu* head;
Stu* p1, * p2;
n = 0;
p1 = p2 = (Stu*)malloc(LEN); //开辟一个新单元 malloc需要头文件#include(stdlib.h) 内存分配函数
scanf("%ld,%f", &p1->num, &p1->score); //输入第一个学生的学号和成绩
head = NULL;
while (p1->num != 0)
{
//n++;
n = n + 1;
if (n == 1)
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
p1 = (Stu*)malloc(LEN); //开辟动态存储区,把起始地址赋给p1
scanf("%ld,%f", &p1->num, &p1->score); //输入其他学生的学号和成绩
//char c;
//while ((c = getchar()) != '\n');
}
p2->next = NULL;
return head;
}
int main()
{
Stu* pt;
pt = creat(); //函数返回链表第一个结点的地址
printf("\n num:%ld\n score:%5.1f\n", pt->num, pt->score); //输出第一个结点的成员值
//free(Stu); //释放结构体
return 0;
}
- #define _CRT_SECURE_NO_WARNINGS
- #include<stdio.h>
- #include<stdlib.h>
- #define LEN sizeof(Stu) //宏替换 LEN代表struct student
- //类型数据的长度 sizeof是 求字节数运算符
- typedef struct Student
- {
- long num;
- float score;
- struct Student* next;
- }Stu;
- int n; //n为全局变量,本文件中各模块均可使用它
- Stu* creat(void) //定义结构函数,此函数返回一个指向 链表头的指针
- {
- Stu* head;
- Stu* p; /*------------不需要那么多指针---------------*/
- n = 0;
- p = (Stu*)malloc(LEN); //开辟一个新单元 malloc需要头文件#include(stdlib.h) 内存分配函数
- if (!p)
- {
- printf_s("内存申请失败\n");
- return NULL;
- }
- scanf_s("%ld%*c%f", &p->num, &p->score); //输入第一个学生的学号和成绩
- head = NULL;
- while (p->num != 0)
- {
- n = n + 1;
- if (n == 1)
- head = p;/*------------第一次时赋值给head---------------*/
- p = p->next;/*------------以后每次指向自身的下个节点---------------*/
- p = (Stu*)malloc(LEN); //开辟动态存储区,把起始地址赋给p1
- if (!p)
- {
- printf_s("内存申请失败\n");
- return head;
- }
- scanf_s("%ld%*c%f", &p->num, &p->score); //输入其他学生的学号和成绩
- }
-
- return head;
- }
- int main()
- {
- Stu* pt;
- pt = creat(); //函数返回链表第一个结点的地址
- printf("\n num:%ld\n score:%5.1f\n", pt->num, pt->score); //输出第一个结点的成员值
- return 0;
- }
复制代码
|
|