Topic five: Print the list from the tail to the head

////////////////////////////////////////////////// ////////////////////////////////////////////
// 8. title five : list print head from the tail

@ Method a: time complexity of O (n), the spatial complexity of O (n-) 
Template <typename the TYPE> void ReversePrintList1 (ListNode <the TYPE> * • pNode) 
{ 
    Assert (NULL ! = • pNode); 
    Stack <ListNode <the TYPE> *> stStack;
     the while (• pNode) 
    { 
        stStack.push (• pNode); 
        • pNode = pNode-> m_pNextNode; 
    } 
    COUT << " list reverse printing: " << endl;
     the while (! stStack.empty ()) 
    { 
        ListNode <the TYPE > * = pTmpNode stStack.top ();
        printf(


    " % 02d -> " , pTmpNode-> m_stData); 
        stStack.pop (); 
    } 

    the putchar ( 10 ); 

} 


// Method two: recursive (recursive stack implementation is similar)
 // time complexity of O (n) space complexity O (the n-)
 // Note: If the list is very long, it will lead to a deep level function calls, resulting in a function call stack overflow! ! ! 
Template <typename the TYPE> void ReversePrintLisHEAP_TYPE (ListNode <the TYPE> * • pNode) 
{ IF (! • pNode) 
    { return ; 
    } 
    ReversePrintLisHEAP_TYPE (• pNode -> m_pNextNode); 
    the 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;

}

Guess you like

Origin www.cnblogs.com/yzdai/p/11258607.html