递归或者翻转,递归空间换时间
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
std::vector<int> res;
recursion(head, res);
return res;
}
private:
void recursion(ListNode *head, std::vector<int> &res) {
if (head == nullptr) {
return ;
}
recursion(head->next, res);
res.push_back(head->val);
}
};