C语言,简单的动态链表实现(demo)

#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Student)

//用结构体、内存函数,指针,常用数据类型实现一个动态链表
struct Student{
int sno;
int name;
int gender;
struct Student * next_p;
};

struct Student * init_lb();
struct Student * creat_item(struct Student * befor_p);
//统计链表元素的个数
static int stu_count = -1;

int main()
{
 
struct Student * now_p=NULL, * next=NULL, * head;
//初始化链表
head = init_lb();
//输入链表的元素
do{
now_p = creat_item(now_p);
//如果是第一个元素
if(stu_count == 0){
head = now_p;
next = now_p;
}
next->next_p = now_p;
next = now_p;
now_p = NULL;
stu_count++;
}while(next->sno);

//输出链表的数据
struct Student * p = head;
do{
printf("sno=%d,name=%d,gender=%d\n", p->sno, p->name, p->gender);
p = p->next_p;
}while(p != NULL);

return 0;
}

//创建链表元素
struct Student * creat_item(struct Student * befor_p){
if(stu_count == -1){
printf("请先初始化链表\n");
exit(1);
}
befor_p = (struct Student *)malloc(LEN);//上一个元素的指针部分址向当前元素
scanf("%d%d%d", &befor_p->sno, &befor_p->name, &befor_p->gender);
befor_p->next_p = NULL;
return befor_p;
}

//初始化链表
struct Student * init_lb(){
stu_count = 0;
struct Student * head = NULL;
return head;
}
posted @ 2022-04-16 20:40  帅哥才  阅读(168)  评论(0编辑  收藏  举报