题目:输入一个链表的头节点,从尾到头打印链表。
分析:有两种思路,1、借助栈,从头到尾遍历链表将值存入栈中,然后输出栈中的值即可。2、可以使用递归,递归的本质就是一个栈结构,但是当链表很长的时候,会导致函数调用的层级很深,从而导致函数调用栈溢出,这里仅给出解法。
/*解法1*/
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
vector<int> printListFromTailToHead(ListNode*phead)
{
vector<int> result;
stack<int> nodes;
while(phead!=NULL)
{
nodes.push(phead->val);
phead=phead->next;
}
while(!nodes.empty())
{
cout<<nodes.top()<<endl;
result.push_back(nodes.top());
nodes.pop();
}
return result;
}
/*解法二*/
vector<int> printListFromTailToHead(ListNode*phead)
{
vector<int> result;
FromTailToHead(phead,result);
return result;
}
void FromTailToHead(ListNode*phead,vector<int> &ref)
{
if(phead==NULL)
return;
FromTailToHead(phead->next,ref);
cout<<phead->val<<endl;
ref.push_back(phead->val);
}