题目:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
分析:
存到数组里通过reverse翻转一下就行
解答:
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
ListNode* p = head;
if(p == NULL)
return res;
while(p != NULL){
res.push_back(p->val);
p = p->next;
}
reverse(res.begin(), res.end());
return res;
}
};
执行用时:4 ms, 在所有 C++ 提交中击败了87.58%的用户
内存消耗:8.3 MB, 在所有 C++ 提交中击败了90.88%的用户