<span>C++面试题:从尾到头打印链表</span>
题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。(前提:不能改变链表的结构)
1、“后进先出”,可以用栈实现这种顺序
代码:
#include <iostream>
#include <stack>
using namespace std;
struct ListNode
{
int m_nValue;
ListNode* m_pNext;
};
void PrintReversingly(ListNode* pHead)
{
std::stack<ListNode*> nodes ;
ListNode* pNode = pHead;
while(pNode != NULL)
{
nodes.push(pNode);
pNode = pNode->m_pNext;
}
while(!nodes.empty())
{
pNode = nodes.top();
printf("%d\t",pNode->m_nValue);
nodes.pop();
}
}
int main(void) {
struct ListNode a ={1,NULL},b={4,NULL},c={3,NULL},d={9,NULL};
a.m_pNext = &b;
b.m_pNext = &c;
c.m_pNext = &d;
PrintReversingly(&a);
return 0;
}
运行结果:
9 3 4 1
2、递归:在本质就是一个栈结构
代码:
#include <iostream>
#include <stack>
using namespace std;
struct ListNode
{
int m_nValue;
ListNode* m_pNext;
};
void PrintReversingly(ListNode* pHead)
{
if(pHead != NULL)
{
if(pHead->m_pNext != NULL)
{
PrintReversingly(pHead->m_pNext);
}
printf("%d\t", pHead->m_nValue);
}
}
int main(void) {
struct ListNode a ={1,NULL},b={4,NULL},c={3,NULL},d={9,NULL};
a.m_pNext = &b;
b.m_pNext = &c;
c.m_pNext = &d;
PrintReversingly(&a);
return 0;
}
运行结果:
9 3 4 1
3、总结
方法二的代码看起来简洁,但当链表非常长的时候,就会导致函数调用的层级很深,可能导致函数调用栈溢出。显然方法一较为合适。
摘自《剑指Offer》