参考
- 《剑指offer》
从尾到头打印链表
题目
输入一个链表的头节点,从尾到头反过来打印出每个节点的值
链表节点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
解法
栈
通常打印是一个只读操作,不希望打印时修改内容,所以解决这个问题肯定要遍历链表。要按与遍历相反的顺序输出节点,就是先进后出,可以使用栈实现。每经过一个节点,把该节点放到一个栈中。当遍历完整个链表后,再从栈顶开始逐个输出节点的值
#include<stack>
void PrintListReversingly_Iteratively(ListNode* pHead)
{
stack<ListNode*> nodes;
ListNode* pNode = pHead;
while (pNode != nullptr)
{
nodes.push(pNode);
pNode = pNode->m_pNext;
}
while (!nodes.empty())
{
pNode = nodes.top();
printf("%d\t", pNode->m_nValue);
nodes.pop();
}
}
递归
void PrintListReversingly_Iteratively(ListNode* pHead)
{
if (pHead != nullptr)
{
if (pHead->m_pNext != nullptr)
{
PrintListReversingly_Iteratively(pHead->m_pNext);
}
printf("%d\t", pHead->m_nValue);
}
}