链表的学习及认识
链表是一种常见的基础数据结构,利用在每一个节点里存到下一个节点的指针的方式进行存储和读取,使用链表结构可以克服数组链表需要预先知道数据大小的缺点,链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理。但是链表失去了数组随机读取的优点,同时链表由于增加了结点的指针域,空间开销比较大。
链表打的创建
链表的创建就是用结构体中的指针来不断的指向下一个链表数据地址来创建链表。
struct Student//定义结构体
{
int num;
int socre;
char *name;//指针
};
struct Student* InitStudent()//为存储链表数据
{
struct Student *str1;//头结点
struct Student *str2;//用于保证链表连接正常的功能节点
struct Student *str3;//用于创建链表的新节点
str1=(struct Student *)malloc(sizeof(struct Student));//申请头结点
str1->Score=99;
str1->Num=1;
str2=str1;
while(str2->Score>50)
{
str3=(struct Student *)malloc(sizeof(struct Student));//申请指针空间,用于创建链表的下一个节点
str2->Pnext=str3;//将功能节点 的指针指下一个节点,即上一行申请的新节点
str3->Num=str2->Num+1;
str3->Score=str2->Score-1;
str2=str3;//将新节点的地址给功能节点
}
return str1;
}
void print(struct Student str)//读取链表数据
{
struct Student *p;
p=&str;//先指向头节点
while(p!=NULL)
{
printf("姓名:%s,学号:%d,成绩:%d\n",p->Name,p->No,p->score );
p=p->Pnext;//指向下一组链表地址
}
}
链表的插入
链表的插入是将新建的节点插入原本连接的两个节点之间,将原本前一个节点的指针指向新节点,再将新节点的指针指向后一个节点
struct Student* InitStudent()
{
struct Student *head;//前节点
struct Student *new;//新节点
struct Student *end;//后节点
head=(struct Student *)malloc(sizeof(struct Student));//申请前结点空间
end=(struct Student *)malloc(sizeof(struct Student));//申请后节点空间
head->Pnext=end;//前后节点连接
head->Score=99;//赋值
head->Num=1;//赋值
end->Score=98;//赋值
end->Num=2;//赋值
while(end->Score>50)
{
new=(struct Student *)malloc(sizeof(struct Student)); //申请新节点空间
new->Pnext=head->Pnext;//将新节点的指针指向前节点的指针
head->Pnext=new;//将前节点指针指向新节点
new->Num=end->Num;
new->Score=end->Score;
end->Num=end->Num+1;
end->Score=end->Score-1;
}
return head;
}
链表的删除、查找、修改
链表的删除、查找、修改方式 都差不多,都是先通过查找来执行进一步的操作,删除还需进行释放空间的操作
struct Student* deleStudent(struct Student *str)
{
struct Student *curry=str;
struct Student *pre;
pre=(struct Student *)malloc(sizeof(struct Student));
int d;
printf("请输入要删除的学号\n");
scanf("%d",&d);
while(curry!=NULL&&curry->Pnext!=NULL)
{ if(curry->Pnext->Num==d)//判断需要查找、删除、修改的节点
{
pre=curry;//删除操作
curry=curry->Pnext;//删除操作
break;//修改操作是将上两行代码换为赋值即可
}
curry=curry->Pnext;
}
pre->Pnext=curry->Pnext;
free(curry);//释放节点空间,此为删除操作,查找、修改这行不需要也不能要
return str;
}
链表的学习一开始是有些困难的但只要能理解它的逻辑结构就不会太困难。