我们之前用c语言实现了双向带头循环链表
本文我们用c++实现
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; struct Node { int _val; struct Node* _prev; struct Node* _next; Node(int x = -1) { _val = x; _prev = nullptr; _next = nullptr; } ~Node() {} }; class LTNode { public: LTNode() { head = new Node(); head->_prev = head; head->_next = head; } ~LTNode() { } void LTPushBack(int val) { Node* tmp = new Node(val); if (isEmpty()) { head->_next = tmp; tmp->_next = head; head->_prev = tmp; tmp->_prev = head; } else { Node* tail = head->_prev; tail->_next = tmp; tmp->_prev = tail; tmp->_next = head; head->_prev = tmp; } } void LTPushFront(int val) { Node* newnode = new Node(val); newnode->_next = head->_next; newnode->_prev = head; head->_next->_prev = newnode; head->_next = newnode; } void LTPopBack() { Node* tail = head->_prev; Node* tailprev = tail->_prev; delete tail; tailprev->_next = head; head->_prev = tailprev; } void LTPopFront() { Node* first = head->_next; Node* second = first->_next; head->_next = second; second->_prev = head; delete first; } bool isEmpty() const { return (head->_next == head && head->_prev == head); // 判断链表是否为空 } void Print() { Node* cur = head->_next; cout << "哨兵位<=>"; while (cur != head) { cout << cur->_val << "<=>"; cur = cur->_next; } cout << "哨兵位" << endl; } Node* LTFind(int x) { Node* cur = head->_next; while (cur != head) { if (cur->_val == x) { return cur; } cur = cur->_next; } return nullptr; } void LTInsert(Node* pos, int x)//在pos之前插入 { Node* newnode = new Node(x); Node* posprev = pos->_prev; posprev->_next = newnode; newnode->_next = pos; newnode->_prev = posprev; pos->_prev = newnode; } void LTErase(Node* pos) { Node* posprev = pos->_prev; Node* posnext = pos->_next; posprev->_next = posnext; posnext->_prev = posprev; delete pos; } private: Node* head; }; int main() { LTNode l1; l1.LTPushBack(1); l1.LTPushBack(2); l1.LTPushBack(3); l1.LTPushBack(4); l1.LTPushBack(4); l1.Print(); l1.LTInsert(l1.LTFind(2), 2); l1.LTInsert(l1.LTFind(1), 0); l1.Print(); l1.LTErase(l1.LTFind(0)); l1.Print(); l1.LTPushFront(0); l1.Print(); l1.LTPopBack(); l1.LTPopFront(); l1.Print(); return 0; }