C++链表(简单实现增删改查)

补充之前有一篇博客,实现简单的增删改查功能

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;
	
	}
}




 

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值