递归的本质是栈,能用栈解决的问题都可转换为递归的程序结构。
链表结点做如下定义:
struct ListNode
{
int val;
ListNode* next;
};
这是一道典型的“先进后出”的案例,先进后出,我们可以使用 stack 实现这种顺序。
void PrintListReversely_Iteratively(ListNode* pHead)
{
std::stack<ListNode*> nodes;
while (pNode)
{
nodes.push(pNode);
pNode = pNode->next;
}
while(!nodes.empty())
{
print("%d\t", nodes.top()->val);
nodes.pop();
}
};
既然想到了用栈来实现这一函数,而递归的本质是一个栈结构,于是很自然地想到用递归来实现。
void PrintListReversely_Recursively(ListNode* pHead)
{
if (pHead)
{
if (pHead->next)
PrintListReversely_Recursively(pHead->next);
print('%d\t', pHead->val);
// 如果将这条打印语句,放在第二条 if 判断之前,就是顺序式的了
}
}