单链表的定义
单链表是线性结构,每个结点都有一个数据域和指针域,用以指向后继结点,可以通过前驱结点中的指针域中的地址信息找到后继结点的位置,所以链表有一个缺点就是不能直接找到某个结点,而是要从头结点开始依次查找,即链表不支持随机访问。
结构体表示如下:
#include <iostream>
using namespace std
;
typedef struct
Node
{
int data
;
sruct Node
* next
;
}Node
;
int main(){
...
return 0;
}
单链表的基本操作
初始化
创建头结点保证头指针始终不为NULL,如果为空表则头结点的next指针为NULL
Node
* InitList(){
Node
* headNode
= (Node
*)malloc(sizeof(Node
));
Node
-> next
= NULL;
return headNode
}
创建结点
创建一个结点,结点的数据域必须有值
Node
* CreateElem(int data
){
Node
* Newelme
= (Node
*)malloc(sizeof(Node
));
Newelem
-> data
= data
;
Newelem
-> next
= NULL;
return Newelem
;
}
插入结点
头插法
void InserList(Node
* L
,int data
)
{
Node
* p
=Newelem(data
);
Node
* r
= L
;
while(1){
if(r
-> next
== NULL){
r
-> next
= p
;
return;
}else
{
r
= r
-> next
;
}
}
}
尾插法
void InsertList(Node
* L
,struct student data
){
Node
* P
= Newelem(data
);
P
-> next
= L
-> next
;
L
-> next
= P
;
}
打印链表
void PrintList(Node
* HeadList
){
Node
* Pmov
= HeadList
-> next
;
while(Pmov
){
printf("%d",Pmov
.data
);
Pmov
= Pmov
-> next
;
}
}
删除结点
void DeleteList(Node
* L
,int data
){
Node
* p
= L
-> next
;
Node
* q
= L
;
if (p
== NULL){
printf("空链表,无法执行删除操作");
}
else
{
while(p
-> data
!= num
){
q
= q
-> next
;
p
= p
-> next
;
if(p
== NULL){
printf("已查找完毕,没有找到储存数据为data的结点");
return;
}
}
q
-> next
= p
-> next
;
free(q
);
}
}
主函数
int main(){
Node
* L
= InitList();
InsertList(L
,1);
InsertList(L
,2);
InsertList(L
,3);
InsertList(L
,4);
printList(L
);
DeleteList(L
,data
);
printList(L
);
return 0;
}
总结
学习了单链表的基本操作后,以后可以设计一个基本的学生管理系统