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 }