有头链表类似于java的list,用于操作多个结构体(对象)
有头链表与无头链表的区别
无头链表是链表中所有的对象都有数据,有头链表是链表中存在一个没有保存数据功能的对象,一般是在表头的位置
有头链表的作用
有头链表的作用是辅助增加对象,插入对象,删除对象
增加对象的案例
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Student{
int id;
char name[12];
Student* next;
};
Student head={0};
void add(Student* s){
s->next=head.next;
//当前对象的下一个对象应该是原来链表头指向的对象
head.next=s;
//链表头应该指向当前对象
}
int main(){
printf("请问要添加几个学生数据\n");
int count;
scanf("%d",&count);
for(int i=0;i<count;i++){
int id;char name[12];
Student* student=(Student*)malloc(sizeof(Student));
printf("请输入学生id\n");
scanf("%d",&id);
printf("请输入学生name\n");
scanf("%s",&name);
student->id=id;
strcpy(student->name,name);
add(student);
}
if(count!=0){
Student* p=&head;
int i=0;
while(p){
if(i!=0){
printf("添加的学生id为%d,名字为%s\n",p->id,p->name);
}
i++;
p=p->next;
}
}else{
printf("谢谢使用");
}
return 0;
}