//////////////////////////////////////////////////////////////////////////////////////////////
// 8.题目五:从尾到头打印链表
// 方法一:时间复杂度O(n),空间复杂度O(n) template <typename TYPE> void ReversePrintList1(ListNode<TYPE>* pNode) { assert(NULL != pNode); stack<ListNode<TYPE>*> stStack; while (pNode) { stStack.push(pNode); pNode = pNode->m_pNextNode; } cout << "链表逆序打印: " << endl; while (!stStack.empty()) { ListNode<TYPE>* pTmpNode = stStack.top(); printf("%02d -> ", pTmpNode->m_stData); stStack.pop(); } putchar(10); } // 方法二:递归实现(递归实现也是类似栈实现) // 时间复杂度O(n), 空间复杂度O(n) // 注意:如果链表非常长,会导致函数调用层级很深,从而导致函数调用栈溢出!!! template <typename TYPE> void ReversePrintLisHEAP_TYPE(ListNode<TYPE>* pNode) { if (!pNode) { return; } ReversePrintLisHEAP_TYPE(pNode->m_pNextNode); printf("%02d -> ", pNode->m_stData); } void ReversePrintListTestFunc() { cout << "\n\n --------------- ReversePrintListTestFunc Start -------------->" << endl; const int MAX_LIST_NODE_COUNT = 10; int aiArray[MAX_LIST_NODE_COUNT] = {0}; INITIALIZE_ARRAY(aiArray, MAX_LIST_NODE_COUNT); TRAVERSAL_ARRAY(aiArray, MAX_LIST_NODE_COUNT); CSingleList<int>* pList = new CSingleList<int>(); if (!pList) { return; } for (int i = 0; i < MAX_LIST_NODE_COUNT; i++) { pList->Insert(aiArray[i]); } pList->Traversal(); ReversePrintList1(pList->GetHeadNode()); cout << "递归实现链表逆序打印: " << endl; ReversePrintLisHEAP_TYPE(pList->GetHeadNode()); putchar(10); delete pList; pList = NULL; cout << "\n\n --------------- ReversePrintListTestFunc End -------------->" << endl; }
原文地址:https://www.cnblogs.com/yzdai/p/11258607.html
时间: 2024-11-05 20:49:35