从尾到头打印链表

//
void printList(ListNode* pHead)
{
    std::stack<ListNode*> printStack;
    ListNode* pTemp = pHead;

    while (pTemp != nullptr)
    {
        printStack.push(pTemp);
        pTemp = pTemp->pNext;
    }
    while (!printStack.empty())
    {
        cout << printStack.top()->nValue;
        printStack.pop();
    }
    return;
}
//递归
void printList(ListNode* pHead)
{
    if (pHead == NULL)
        return;
    if (pHead->pNext != NULL)
    {
        printList(pHead->pNext);   //当链表长度过长时,会导致函数调用层级过深,函数调用栈溢出
    }
    cout << pHead->nValue;
    return;
}

 

posted on 2021-01-21 19:59  Noora&w  阅读(50)  评论(0编辑  收藏  举报