您的位置:首页 > 其它

题目6:从尾到头打印链表

2018-03-07 22:58 232 查看
    题目:输入一个链表的头节点,从尾部到头反过来打印出每个节点的值。链表节点定义如下:struct ListNode
{
int m_nKey;
ListNode* m_pNext;

};
        从头到尾打印每个节点的值,我们都知道只要从头到尾遍历一遍就可以。现在我们需要从尾到头打印每个节点的值,我们有两个思路,其一就是从头到遍历,同时将每个节点的值存到栈中。其二就是利用递归。

一、利用栈先进后出void PrintListReversingly_Iteratively(ListNode* pHead)
{
std::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_Recursively(ListNode* pHead)
{
if(pHead != nullptr)
{
if (pHead->m_pNext != nullptr)
{
PrintListReversingly_Recursively(pHead->m_pNext);
}

printf("%d\t", pHead->m_nValue);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: