【C++】简单的链表示例

#include <iostream>

using namespace std;

typedef struct Person
{
	Person* next;
	string name;
}*P_Person,S_Person;

S_Person list_head_node;//链表头结点,方便对链表进行操作

void list_init(void)//链表初始化
{
	list_head_node.next = NULL;
	list_head_node.name = "head node";
}

int list_add(string name)//根据名字新增一个节点
{
	P_Person new_node = new S_Person;

	if (new_node == NULL)
		return 0;

	new_node->name = name;
	new_node->next = NULL;

	P_Person cur_node = &list_head_node;

	while (cur_node->next != NULL)
	{
		cur_node = cur_node->next;
	}

	cur_node->next = new_node;
	return 1;
}

int list_find(string name)//根据名字查找节点
{
	P_Person cur_node = list_head_node.next;

	while (cur_node != NULL)
	{
		if (cur_node->name == name)
			return 1;
	
		cur_node = cur_node->next;
	}

	return 0;
}

int list_del(string name)//根据名字删除节点
{
	P_Person cur_node = list_head_node.next;
	P_Person pre_node = &list_head_node;

	while (1)
	{
		if (cur_node == NULL)
			return 0;
		
		if (cur_node->name == name)
		{
			pre_node->next = cur_node->next;
			delete cur_node;
			return 1;
		}

		pre_node = cur_node;
		cur_node = cur_node->next;
	}
}

void list_print()//打印链表
{
	P_Person cur_node = list_head_node.next;
	int i = 0;

	while (cur_node != NULL)
	{
		cout << "name" << i << " : " << cur_node->name << endl;
		i++;
		cur_node = cur_node->next;
	}
}

int main()//测试代码
{
	list_init();
	list_add("zhangsan");
	list_add("lisi");
	list_add("wangwu");
	list_add("xiaoliu");
	list_add("xiaoming");
	list_print();

	if (list_find("wangwu"))
	{
		cout << "find wangwu" << endl;
	}

	list_del("wangwu");

	if (list_find("wangwu"))
	{
		cout << "find wangwu" << endl;
	}
	else
	{
		cout << "no wangwu" << endl;
	}

	list_print();
}

测试结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值