#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();
}
测试结果