链表之前一直没掌握(有些懒惰了),希望通过这次的学习,能掌握链表!
//链表与数组结合思考
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define LEN sizeof(struct Student) //Student结构的大小
struct Student *creat(); //创建链表
void print(struct Student *head); //打印链表,没有参数也对好像
struct Student
{
long num;
double score;
struct Student *next;
};
int n; // 全局变量,用来记录存放了多少数据
int main()
{
struct Student *stu;
stu = creat();
print(stu);
printf("\n\n");
return 0;
}
struct Student *creat()
{
Student *head;
Student *p1,*p2;
p1=p2=(Student *)malloc(LEN); //LED 结构体大小
printf("请输入学号:");
scanf("%ld",&p1->num);
printf("请输入分数:");
scanf("%lf",&p1->score);
head = NULL;
n = 0;
while( p1->num ){
n++;
if( 1 == n){
head = p1;
}
else{
p2->next = p1;
}
p2 = p1;
p1 = (Student *)malloc(LEN); //再一次创建一个结构体所用空间,就是新创建的节点
printf("请输入学号:");
scanf("%ld",&p1->num);
printf("请输入分数:");
scanf("%lf",&p1->score);
}
p2->next = NULL; //循环退出后,使(p2指向的节点)最后操作的节点的 next 指向 NULL
return head; //返回整个链表的首地址
}
void print(struct Student *head)
{
Student *p;
p = head;
if(NULL != head) //判断,前面步骤没错便无关紧要了
do{
printf("学号为%ld的学生成绩为:%.2lf\n",p->num,p->score);
p = p->next;
} while(NULL != p);
}