#include <stack>
// 从尾到头打印链表
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
// 方案一
// 将链表放到栈中,再从栈顶逐个输出
void PrintListReversingly_Iteratively(ListNode* pHead)
{
std::stack<ListNode*> nodes;
ListNode* pNode = pHead;
while(NULL != pNode)
{
nodes.push(pNode);
pNode = pNode->m_pNext;
}
while (!nodes.empty())
{
pNode = nodes.top();
printf("%d\t", pNode->m_nKey);
nodes.pop();
}
}
// 方案二
// 递归实现(本质上递归就是一个栈结构)
// 不过有个问题,链表过长时,会导致函数调用的层级很深,
// 从而导致函数调用栈溢出,因此方案一显式用栈基于循环实现的
// 代码的鲁棒性要好一些
void PrintListReversingly_Recursively(ListNode* pHead)
{
if (pHead != NULL)
{
if(pHead->m_pNext != NULL)
{
PrintListReversingly_Iteratively(pHead->m_pNext);
}
printf("%d\t", pHead->m_nKey);
}
}
来源:剑指offer名企面试官精讲典型编程题