目录
本节分上下两节,主要是对链表进行一个实操演练。本章节小节记录的是数据链表的学生管理系统实现方法,主要有链表的创建、链表插入、链表遍历,此前所学还是单向链表,后续会退出单向循环链表、双向链表、双向循环链表等;
1.main函数设计
int main()
{
helpMessage();
while(1){
char cmd[64] = "";
cout<<"请输入操作指令: ";
cin >> cmd;
if(strcmp(cmd,"help") == 0){
helpMessage();
}else if(strcmp(cmd,"insert") == 0){
cout << "-------insert-------"<<endl;
}else if(strcmp(cmd,"print") == 0){
cout << "-------print-------"<<endl;
}else if(strcmp(cmd,"search") == 0){
cout << "-------search-------"<<endl;
}else if(strcmp(cmd,"delete") == 0){
cout << "-------delete-------"<<endl;
}else if(strcmp(cmd,"free") == 0){
cout << "-------free-------"<<endl;
}else if(strcmp(cmd,"clear") == 0){
system("cls");
}else if(strcmp(cmd,"quit") == 0){
return 0;
}
}
return 0;
}
link.cpp
#include "link.h"
Link::Link()
{
}
void helpMessage()
{
cout<<" *********************************"<<endl;
cout<<" * help:帮助信息 *"<<endl;
cout<<" * insert:插入链表节点 *"<<endl;
cout<<" * print:遍历链表 *"<<endl;
cout<<" * search:查询链表某个节点 *"<<endl;
cout<<" * delete:删除链表某个节点 *"<<endl;
cout<<" * free:释放整个链表 *"<<endl;
cout<<" * quit:退出程序 *"<<endl;
cout<<" * clear:清空屏幕 *"<<endl;
cout<<" *********************************"<<endl;
}
2.定义Node节点类型
struct STU_NODE{
//数据域
int num;
char name[32];
//指针域
STU_NODE *next;
};
3.链表插入结点
在main函数中调用插入函数、打印函数
插入结点函数实现(头插法)
//链表插入之 在头部之前插入(头插法)
STU_NODE *insertLink(STU_NODE *head,STU_NODE tmp){
//从堆区申请带插入的节点空间
STU_NODE *pnode = new STU_NODE();
//给空间赋值
*pnode = tmp;
pnode->next = nullptr;
//判断链表这个结点为不为空
if(nullptr == head){ //不存在
head = pnode;
}else{//链表存在
pnode->next = head;
head = pnode;
}
return head;
}
插入结点函数实现(尾插法)
//链表插入之 在尾部之后插入(尾插法)
STU_NODE *insertLink(STU_NODE *head,STU_NODE tmp){
//从堆区申请带插入的节点空间
STU_NODE *pnode = new STU_NODE();
//给空间赋值
*pnode = tmp;
pnode->next = nullptr;
//判断链表这个结点为不为空
if(nullptr == head){ //不存在
head = pnode;
}else{//链表存在
//寻找尾节点
STU_NODE *pnewnode = head;
while(pnewnode->next != nullptr)
pnewnode = pnewnode->next;
//在尾节点插入pnode
pnewnode->next = pnode;
}
return head;
}
遍历链表函数实现
void printLink(STU_NODE *head){
if(nullptr == head){ //不存在
cout<<"Link is not exist"<<endl;
return;
}
STU_NODE *node = head;
while(node != nullptr){
cout<<node->num<<" "<<node->name<<endl;
node = node->next;
}
return;
}