c++的链表通过定义具有节点指针和节点数据的结构体,并且使用指针将他们联系在一起,使得通过至少一个指针便可以管理整个链表的数据。
使用c++实现链表的增删改查
具体代码如下
#include <iostream>
using namespace std;
struct ListNode { int id; string name; ListNode* next; };
ListNode* initList()//初始化链表
{ ListNode* head = new (nothrow) ListNode;
head->next = nullptr; return head; }
void DestroyList(ListNode* head)//销毁列表
{ ListNode* tmp;
while (head != nullptr) { tmp = head->next; delete head; head = tmp; } }
bool HeadInsert(ListNode* head,const int& id,const string& name)//头插法
{ if (head == nullptr) return false;
ListNode* tmp = new ListNode{ id,name };
tmp->next = head->next; head->next = tmp;
return true; }
bool TailInsert(const ListNode* head, const int& id, const string& name)//尾插法
{ if (head == nullptr || head->next == nullptr) return false;
ListNode* tmp;
tmp = head->next;
while (tmp->next != nullptr) tmp = tmp->next;
ListNode* tmp2 = new ListNode{ id,name,nullptr };
tmp->next = tmp2; return true; }
void TraverseList(const ListNode* head)//遍历链表并输出
{ if (head == nullptr) return;
ListNode* tmp; tmp = head->next;
while (tmp != nullptr) { cout << tmp->id << "----" << tmp->name << endl; tmp = tmp->next; } }
bool DelHead(ListNode* head)//从头部删除一个节点
{ if (head == nullptr || head->next == nullptr) return false;
ListNode* tmp = head->next->next;
delete head->next;
head->next = tmp;
return true; }
bool DelTail(const ListNode* head)//从尾部删除一个节点
{ if (head == nullptr || head->next == nullptr) return false;
ListNode* tmp;
tmp = head->next;
while (tmp->next->next != nullptr) tmp = tmp->next;
delete tmp->next;
tmp->next = nullptr;
return true; }
ListNode* SearchNode(const ListNode* head, int id, string name)//查找并修改节点数据
{ if (head == nullptr) return nullptr;
ListNode* tmp;
tmp = head->next;
while (tmp != nullptr)
{ if((tmp->id==id)&&(tmp->name==name) ) return tmp; tmp = tmp->next; }
return nullptr; }
int main()
{ ListNode* head = initList();
HeadInsert(head,12,"tom");
HeadInsert(head, 15, "ford");
HeadInsert(head, 5, "li");
TailInsert(head, 90, "kk");
SearchNode(head, 15, "ford")->id = 6;
DelTail(head); TraverseList(head);
DestroyList(head);//测试代码 }
运行成功。