The traversal of the doubly-linked list is much more convenient than a one-way list, so the inverse method is much richer than a single-linked list, because it can be traversed from the back, so it can be manipulated like an inverse array, or it can be reversed based on the characteristics of a single-linked list, or it can be reversed with the unique characteristics of a doubly Here's how:
The class definition for the linked list is as follows:
Typedef int datatype;class dsnode{public:friend class dnslist;dsnode (DataType x= 0): _data (x), _next (null), _prev (null) {}private:dsnode*_prev;dsnode*_next;datatype _data;}; Class dnslist{public:dnslist (): _head (null), _tail (null) {}~dnslist () {_clear ();} Dnslist (const dnslist &l) {dsnode *cur = l._head;while (cur) {PushBack (cur- >_data);}} dnslist operator = (dnslist l) {_clear ();D snode *cur = l._head;while ( cur) {pushback (cur->_data);}} public:// Head Insert/Head delete/tail plug/Tail Delete void pushback (const datatype& x); Void popback ();void Pushfront (const datatype& x); Void popfront ();// Insert/Find/delete Void insert (DSNode* pos, const datatype& x);D Snode* find (const datatype& x); Void Erase ( CONST DATATYPE& X);//void reverse ();//The same spatial complexity does not require a return value of Dnslist* reverse ();// Different spatial complexity returns// print VOID&N with linked list pointersBsp Print ();p rivate:void _clear () {while (_head) {dsnode*cur = _head;_head = _head- >_next;delete cur;}} dsnode *_head;dsnode *_tail;};
In a single space complexity:
1. Swap the contents of the store by traversing through the center and tail pointers to the middle.
void Dnslist::reverse () {Dsnode *begin = _head;dsnode *end = _tail;while (!) ( begin==end| | Begin->_prev==end)) {DataType tmp = Begin->_data;begin->_data = End->_data;end->_data = Tmp;end = end- >_prev;begin = Begin->_next;}}
2. Simply traverse backwards through the head pointer, exchanging the precursors and successors of each node.
void Dnslist::reverse () {Std::swap (_head, _tail);D snode*cur = _head;while (cur) {std::swap (Cur->_next, cur->_ prev); cur = cur->_next;}}
In multiple spatial complexity:
Creates a new doubly-linked list pointer that traverses the target list from front to back/backward forward, inserting the elements of each node into the head/tail.
dnslist* Dnslist::reverse () {dnslist*newlist = new Dnslist;dsnode *cur = _head;while (cur) {Newlist->pushfront (cur- >_data); cur = cur->_next;} return newlist;}
If there are deficiencies or errors, hope to criticize.
This article is from the "Pawnsir It Road" blog, so be sure to keep this source http://10743407.blog.51cto.com/10733407/1747812
Three ways to "summarize" the inverse doubly linked list