#define _CRT_SECURE_NO_WARNINGS 1#include#include using namespace std;template struct Node { Node(const T& d) : _next(NULL) , _prev(NULL) , _data(d) {} Node * _next; Node * _prev; T _data; }; template class Dlist { public: Dlist() :_head(NULL) ,_tail(NULL) {} ~Dlist() { Node * cur = _head; while(cur) { Node * del = cur; cur=cur->_next; delete del; del = NULL; } } public: void PushBack(const T& d); void PushFront(const T& d); void PopBack(); void PopFront(); void Reverse(); void Print() { Node * cur = _head; while(cur) { cout< _data <<"<=> "; cur=cur->_next; } cout<<"over"< * _head; Node * _tail; };template void Dlist ::PushBack(const T& d){ Node * newNode = new Node (d); if(_head == NULL) { _head = newNode; _tail = _head; } else { _tail->_next = newNode; newNode->_prev = _tail; _tail =newNode; }}template void Dlist ::PushFront(const T& d){ Node * newNode = new Node (d); if(_head == NULL) { _head = newNode; _tail = _head; } else { newNode->_next = _head; _head = newNode; }}template void Dlist ::PopBack(){ if(_head == NULL) return; else if(_head->_next == NULL) { delete _head; _head = NULL; _tail = NULL; } else { _tail=_tail->_prev ; delete _tail ->_next ; _tail->_next = NULL; }}template void Dlist ::PopFront(){ if(_head == NULL) return; else if(_head->_next==NULL) { delete _head; _head=NULL; _tail=NULL; } else { Node * del = _head; _head = _head->_next ; delete del; del = NULL; }}template void Dlist ::Reverse(){ Node * cur = _head; Node * prev = NULL; Node * pnewhead=NULL; while(cur) { prev = cur; cur = cur->_next; prev->_next = pnewhead; pnewhead = prev; } _head = pnewhead; }int main(){ Dlist s1; s1.PushBack(1); s1.PopFront(); s1.Print (); s1.PushBack(2); s1.PushBack(3); s1.PushBack(4); s1.Print (); s1.Reverse (); s1.Print (); s1.PushFront (2); s1.Print (); s1.PopBack(); s1.Print (); s1.PopFront(); s1.Print (); s1.PopFront (); s1.Print (); system("pause"); return 0;}
运行结果如下: