首页 > 其他 > 详细

从尾到头打印链表

时间:2014-02-20 14:31:26      阅读:366      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 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 }
bubuko.com,布布扣

从尾到头打印链表

原文:http://www.cnblogs.com/crazycodehzp/p/3556793.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!