题目描述
输入一个链表的头节点,从尾到头反过来 返回每个节点的值(用数组返回)。
示例
示例1
1 2
| 输入:head = [1,3,2] 输出:[2,3,1]
|
限制:
思路1
利用递归调用函数到最后时,回逆向返回的特点,保存节点的值
递归代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} ListNode(int x, ListNode *p) : val(x), next(p) {} };
class Solution { public: vector<int> reversePrint(ListNode *head) { vector<int> ans; fun(head, ans); return ans; } void fun(ListNode *head, vector<int>& ans) { if (head == nullptr) { return; } fun(head->next, ans); ans.push_back(head->val); } };
|