面试题5:从尾到头打印链表

面试题5

链表结构:

struct ListNode
{
    int       m_nValue;
    ListNode* m_pNext;
};

栈:

注意栈中的类型一定是指针类型,因为每次push进去的是一个指针

#include <stack>

void PrintListReversingly_Iteratively(ListNode* pHead)
{
    std::stack<ListNode*> nodes;

    ListNode* pNode = pHead;
    while(pNode != NULL)
    {
        nodes.push(pNode);
        pNode = pNode->m_pNext;
    }

    while(!nodes.empty())
    {
        pNode = nodes.top();
        printf("%d\t", pNode->m_nValue);
        nodes.pop();
    }
}

递归:

void PrintListReversingly_Recursively(ListNode* pHead)
{
    if(pHead != NULL)
    {
        if (pHead->m_pNext != NULL)
        {
            PrintListReversingly_Recursively(pHead->m_pNext);
        }
 
        printf("%d\t", pHead->m_nValue);
    }
}

 

posted on 2016-07-01 14:18  已停更  阅读(227)  评论(0)    收藏  举报