题目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);
}
}
{
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);
}
}
相关文章推荐
- 题目1511:从尾到头打印链表
- 剑指Offers 题目1511:从尾到头打印链表
- 《剑指Offer》题目——从尾到头打印链表
- 题目1511:从尾到头打印链表
- 题目1511:从尾到头打印链表
- 题目1511:从尾到头打印链表-九度
- 题目1511:从尾到头打印链表
- [Jobdu] 题目1511:从尾到头打印链表——单链表的倒置输出
- 【九度】题目1511:从尾到头打印链表
- 九度oj_题目1511:从尾到头打印链表
- 牛客网 - 剑指Offer - 考点:链表 题目:从尾到头打印链表
- 题目1511:从尾到头打印链表
- 题目5:从尾到头打印链表
- 题目1511:从尾到头打印链表
- 算法题目-从尾到头打印链表
- 题目1511:从尾到头打印链表
- 题目1511:从尾到头打印链表
- 题目:输入一个链表,从尾到头打印链表每个节点的值
- 题目1511:从尾到头打印链表
- 【C++】面试题目:从尾到头打印链表