补充之前有一篇博客,实现简单的增删改查功能
main函数内为测试内容
#include <iostream>
using namespace std;
struct Student
{
int num;
char name[10];
Student *next;
};
Student *head;//全局头节点
//增---新增节点数据
void AddNode();
//删---删除节点数据
void DelectNode();
//改---改变节点数据
void ChangeNode();
//查---查询节点数据
void FindNode();
//获取一个无链接的节点
Student * CreateOneNode();
//显示所有数据
void ShowAllNode();
//创建链表
void CreatLinkedlist();
//main
int main()
{
CreatLinkedlist();
ShowAllNode();
// change();
// show();
// Add();
// show();
// Delect();
// show();
FindNode();
getchar();
getchar();
getchar();
return 0;
}
//具体实现
//-----增-----//
void AddNode()
{
int num;
cout << "请问你在哪个num后插入:num:";
cin >> num;
Student *p = head;
Student *node = CreateOneNode();
Student *bp = head;
while (p != NULL)
{
if (p->num == num)
{
bp = p->next;//bp作为p点的下一个元素
p->next = node;//把p点和新增的node链接起来
node->next = bp;//把node点的下一个元素和bp链接
return;
}
p = p->next;
}
}
//-----删-----//
void DelectNode()
{
cout << "请输入要删除的num:";
int num;
cin >> num;
Student *p = head;
Student *bp = head;
if (num == head->num)//如果是删除头节点
{
head = p->next;
p = head;
return;
}
while (p != NULL)
{
if (p->num == num)
{
bp->next = p->next;//把p点的上一个元素和p点的下一个元素链接起来
delete p;//释放p点的内存
return;
}
bp = p;//bp作为要删除元素的上一个元素
p = p->next;
}
}
//-----改-----//
void ChangeNode()
{
cout << "请输入要修改的num:";
int num;
cin >> num;
cout << "name:";
char name[5];
cin >> name;
Student *p = head;
while (p != NULL)
{
if (p->num == num)
{
strcpy(p->name, name);
}
p = p->next;
}
}
//-----查-----//
void FindNode()
{
cout << "你要查询哪个num的数据:num:";
int num;
cin >> num;
Student *p = head;
while (p!=NULL)
{
if (num==p->num)
{
cout << "num:" << p->num<<endl;
cout << "name:" << p->name<<endl;
return;
}
p = p->next;//p指针后移
}
cout << "no find num:" << num << endl;
}
//-----创建节点-----//
Student * CreateOneNode()
{
Student *p=new Student;
cout << "请输入:\n";
cout << "num:";
cin >> p->num;
cout << "name:";
cin >> p->name;
p->next = NULL;
if (p->num==0)
{
return NULL;
}
return p;
}
//-----创建链表-----//
void CreatLinkedlist()
{
if ((head=CreateOneNode())==NULL)
{
return;
}
Student *p = head;
Student *node;
for (; p!=NULL;)
{
node = CreateOneNode();
p->next = node;
p = node;
}
}
//-----显示全部节点-----//
void ShowAllNode()
{
Student *p = head;
while (p!=NULL)
{
cout << " num :" << p->num << endl;
cout <<" name :"<< p->name<<endl;
p = p->next;
}
}