<OFFER> 06_PrintListInReversedOrder

复制代码
 1 #include<stack>
 2 #include "List.h"
 3 
 4 void PrintListReversingly_Iteratively(ListNode* pHead)
 5 {
 6     std::stack<ListNode*> nodes;
 7 
 8     ListNode* pNode = pHead;
 9     while (pNode != nullptr)
10     {
11         nodes.push(pNode);
12         pNode = pNode->m_pNext;
13     }
14 
15     while (!nodes.empty())
16     {
17         pNode = nodes.top();
18         printf("%d\t", pNode->m_nValue);
19         nodes.pop();
20     }
21 }
22 
23 void PrintListReversingly_Recursively(ListNode* pHead)
24 {
25     if (pHead != nullptr)
26     {
27         if (pHead->m_pNext != nullptr)
28         {
29             PrintListReversingly_Recursively(pHead->m_pNext);
30         }
31         printf("%d\t", pHead->m_nValue);
32     }
33 }
34 
35 void Test(ListNode* pHead)
36 {
37     PrintList(pHead);
38     PrintListReversingly_Iteratively(pHead);
39     printf("\n");
40     PrintListReversingly_Recursively(pHead);
41 }
42 
43 // 1 2 3 4 5
44 void Test1()
45 {
46     printf("\nTest1 begins.\n");
47 
48     ListNode* pNode1 = CreateListNode(1);
49     ListNode* pNode2 = CreateListNode(2);
50     ListNode* pNode3 = CreateListNode(3);
51     ListNode* pNode4 = CreateListNode(4);
52     ListNode* pNode5 = CreateListNode(5);
53 
54     ConnectListNodes(pNode1, pNode2);
55     ConnectListNodes(pNode2, pNode3);
56     ConnectListNodes(pNode3, pNode4);
57     ConnectListNodes(pNode4, pNode5);
58 
59     Test(pNode1);
60 
61     DestroyList(pNode1);
62 }
63 
64 // only one node
65 void Test2()
66 {
67     printf("\nTest2 begins.\n");
68 
69     ListNode* pNode1 = CreateListNode(1);
70 
71     Test(pNode1);
72     DestroyList(pNode1);
73 }
74 
75 // empty list
76 void Test3()
77 {
78     printf("\nTest3 begins.\n");
79     Test(nullptr);
80 }
81 
82 int main()
83 {
84     Test1();
85     Test2();
86     Test3();
87 
88     return 0;
89 
90 
91 }
复制代码

 

posted @   清风oo  阅读(177)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示