Title: Given a head node, flashbacks output a linked list
Solution 1: First reverse the list, in the traversal output
Solution 2: Do not modify the structure of the list itself, the dynamic application of a space, the application of a pointer array, the array of stored pointers to each value of the list, and then iterate over the array output:
void Printlistback (listnode* head) {int n = getlength (head); listnode** p = new Listnode*[n+1];p [n] = Null;int i = 0; listnode* Pnode = head;while (i < n) {P[i] = Pnode;pnode = Pnode->m_pnext;++i;} for (i = n-1; i>= 0; i--) {cout<<p[i]->m_nvalue<< "";}}
Solution 3: The use of stacks, LIFO;
void PrintListBack2 (listnode* head) {stack<listnode> Liststack; listnode* Pnode = Head;while (pnode!=null) {Liststack.push (pnode->m_nvalue);p node = Pnode->m_pnext;} int i = Liststack.size (); for (; i>0;i--) {ListNode p = liststack.top ();cout<<p.m_nvalue<<endl; Liststack.pop ();}} void PrintListBack3 (listnode* head) {stack<listnode*> Liststack; listnode* Pnode = Head;while (pnode!=null) {Liststack.push (Pnode);p node = Pnode->m_pnext;} int i = Liststack.size (); for (; i>0;i--) {listnode* p = liststack.top ();cout<<p->m_nvalue<<endl; Liststack.pop ();}}
Solution 4: Using recursion
void PrintListBack4 (listnode* head) {if (head! = null) {if (Head->m_pnext! = null) {PrintListBack4 (head->m_pnext);} Cout<
Full code:
PrintListBack.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <stack>using namespace std;struct listnode {int M_nval Ue listnode* M_pnext; ListNode (int a): M_nvalue (a), M_pnext (NULL) {}};int getlength (listnode* head) {listnode* Pnode = head;int ncount = 0;while ( pnode!= NULL) {ncount++;p node = pnode->m_pnext;} return ncount;} void Printlistback (listnode* head) {int n = getlength (head); listnode** p = new Listnode*[n+1];p [n] = Null;int i = 0; listnode* Pnode = head;while (i < n) {P[i] = Pnode;pnode = Pnode->m_pnext;++i;} for (i = n-1; i>= 0; i--) {cout<<p[i]->m_nvalue<< "";}} void PrintListBack2 (listnode* head) {stack<listnode> Liststack; listnode* Pnode = Head;while (pnode!=null) {Liststack.push (pnode->m_nvalue);p node = Pnode->m_pnext;} int i = Liststack.size (); for (; i>0;i--) {ListNode p = liststack.top ();cout<<p.m_nvalue<<endl; Liststack.pop ();}} void PrintListBack3 (listnode* head) {stack<listnode*> LISTSTAck listnode* Pnode = Head;while (pnode!=null) {Liststack.push (Pnode);p node = Pnode->m_pnext;} int i = Liststack.size (); for (; i>0;i--) {listnode* p = liststack.top ();cout<<p->m_nvalue<<endl; Liststack.pop ();}} void PrintListBack4 (listnode* head) {if (head! = null) {if (Head->m_pnext! = null) {PrintListBack4 (head->m_pnext);} Cout<
Reverse output of C + + algorithm a linked list