输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。
返回的结果用数组存储。
样例
输入:[2, 3, 5]
返回:[5, 3, 2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
class Solution { public: vector<int> printListReversingly(ListNode* head) { vector<int> r; while (head) { r.push_back(head->val); head = head->next; } return vector<int>(r.rbegin(), r.rend()); } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution { public: vector<int> res;
void reverse(ListNode* head) { if (!head) return; reverse(head->next); res.push_back(head->val); }
vector<int> reversePrint(ListNode* head) { reverse(head); return res; } };
|