题目地址
https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
题目描述:从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
例:
输入:head = [1,3,2]
输出:[2,3,1]
解答
栈/递归,二者本质是相同的(递归本质上是一个栈结构),但当链表长度非常长的时候,会导致函数调用的层次很深,因此函数调用栈可能溢出。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> res;
void order( ListNode* p){
if( !p)
return ;
order(p->next);
res.push_back( p->val);
return ;
}
vector<int> reversePrint(ListNode* head) {
order( head);
return res;
}
};
来源:CSDN
作者:gfnbijsda
链接:https://blog.csdn.net/sd4567855/article/details/104614605