从尾到头打印链表

 1 #include "stdafx.h"
 2 #include <iostream>
 3 #include <exception>
 4 #include <stack>
 5 using namespace std;
 6 
 7 /*从尾到头打印链表*/
 8 /*
 9 题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
10 */
11 struct ListNode
12 {
13     int m_nValue;
14     ListNode* m_pNext;
15 };
16 
17 //根据后进先出的思想,考虑用栈的方法
18 void PrintListReversingly_Iteratively(ListNode* pHead)
19 {
20     std::stack<ListNode*> nodes;
21     ListNode* pNode = pHead;
22     while(pNode!=NULL)
23     {
24         nodes.push(pNode);
25         pNode=pNode->m_pNext;
26     }
27     while(!nodes.empty())
28     {
29         pNode = nodes.top();
30         cout<<pNode->m_nValue<<endl;
31         nodes.pop();
32     }
33 }
34 
35 //根据后进先出的思想,考虑用递归的方法
36 void PrintListReversingly_Iteratively(ListNode* pHead)
37 {
38     if(pHead != NULL){
39         if(pHead->m_pNext != NULL)
40             PrintListReversingly_Iteratively(pHead->m_pNext);
41         cout<<pHead->m_nValue<<endl;
42     }
43 }
44 
45 int _tmain(int argc, _TCHAR* argv[])
46 { 
47     return 0 ;
48 }
原文地址:https://www.cnblogs.com/crazycodehzp/p/3556793.html