思路1:使用棧
思路2:遞歸
1 #include<iostream>
2 #include <stdlib.h>
3 #include <stack>
4
5 using namespace std;
6
7 struct ListNode
8 {
9 int m_nValue;
10 ListNode* m_pNext;
11 };
12
13 ListNode* CreateListNode(int value)
14 {
15 ListNode *pNode = new ListNode();
16 pNode->m_nValue = value;
17 pNode->m_pNext = NULL;
18 return pNode;
19 }
20
21 void PrintListNode(ListNode* pNode)
22 {
23 printf("%d\n", pNode->m_nValue);
24 }
25
26 //打印鏈表
27 void PrintList(ListNode* pHead)
28 {
29 ListNode* pNode = pHead;
30 while(pNode != NULL)
31 {
32 cout << pNode->m_nValue<<" ";
33 pNode=pNode->m_pNext;
34 }
35 cout << endl;
36 }
37
38 //在鏈表結尾添加一個結點
39 void AddToTail(ListNode** pHead, int value)
40 {
41 ListNode* pNew = new ListNode();
42 pNew->m_nValue = value;
43 pNew->m_pNext = NULL;
44
45 if(*pHead == NULL)
46 {
47 *pHead = pNew;
48 }
49 else
50 {
51 ListNode* pNode = *pHead;
52 while(pNode->m_pNext != NULL)
53 pNode = pNode->m_pNext;
54
55 pNode->m_pNext=pNew;
56 }
57
58 }
59
60
61 //方法1: 用棧實現
62 void PrintListReversingly_Iteratively(ListNode* pHead)
63 {
64 ListNode* pNode = pHead;
65 stack<ListNode*> nodes;
66
67 while(pNode != NULL)
68 {
69 nodes.push(pNode);
70 pNode = pNode->m_pNext;
71 }
72
73 while(!nodes.empty())
74 {
75 pNode = nodes.top();
76 cout<<pNode->m_nValue<<" ";
77 nodes.pop();
78 }
79 cout << endl;
80 }
81
82 //方法2: 遞歸
83 void PrintListReversingly_Recursively(ListNode* pHead)
84 {
85 ListNode* pNode = pHead;
86 if(pNode != NULL)
87 {
88 if(pNode->m_pNext != NULL)
89 PrintListReversingly_Recursively(pNode->m_pNext);
90 }
91 cout<<pNode->m_nValue<<" ";
92 }
93
94 // 1->2->3->4->5->6->7
95 int main()
96 {
97 ListNode* pNode1 = CreateListNode(1);
98 PrintList(pNode1);
99
100 AddToTail(&pNode1,2);
101 AddToTail(&pNode1,3);
102 AddToTail(&pNode1,4);
103 AddToTail(&pNode1,5);
104 AddToTail(&pNode1,6);
105 AddToTail(&pNode1,7);
106
107 PrintList(pNode1);
108
109 PrintListReversingly_Iteratively(pNode1);
110 PrintListReversingly_Recursively(pNode1);
111
112 return 0;
113 }
