数据结构<二>双向链表
#include<iostream> using namespace std; struct Node{ int data; Node* prev; Node* next; }; class List{ private: Node* head; public: List(); ~List(); int Length(); bool Empty(); void clear(); void push_front(int x); void push_back(int x); void pop_front(); void pop_back(); void print(); }; List::List(){ head = new Node; head->prev = head->next = head; } List::~List(){ clear(); delete head; } int List::Length(){ Node *q = head->next; int k = 0; while (q != head) { k++; q = q->next; } return k; } bool List::Empty(){ return head->next == head; } void List::push_front(int x){ Node* q = new Node; q->data = x; q->prev = head; q->next = head->next; head->next->prev = q; head->next = q; } void List::push_back(int x){ Node* q = new Node; q->data = x; q->prev = head->prev; q->next = head; head->prev->next = q; head->prev = q; } void List::pop_front(){ if (Empty()) return ; Node *q = head->next; head->next = q->next; q->next->prev = head; delete q; } void List::pop_back(){ if (Empty()) return ; Node *q = head->prev; head->prev = q->prev; q->prev->next = head; delete q; } void List::clear() { Node *p = head->next; while(p != head) { Node *q = p; p = p->next; delete q; } head->next = head; head->prev = head; } void List::print() { Node *q = head->next; while (q != head) { cout<<q->data<<" "; q = q->next; } cout<<endl; } int main() { List l; l.push_back(2); l.push_front(3); l.push_back(4); l.push_front(5); l.push_back(6); l.pop_front(); l.print(); cout<<l.Length()<<endl; return 0; }