题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
非递归解法
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> vec;
while (head)
{
vec.push_back(head->val);
head = head->next;
}
reverse(vec.begin(), vec.end());
return vec;
}
};
递归解法
对当前的head,求解reversePrint(head->next),再push_back head->val
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
if (!head)
return {};
auto vec = reversePrint(head->next);
vec.push_back(head->val);
return vec;
}
};