题目中涉及逆序首先想到的是栈结构,本题可以额外使用一个栈保存结果再弹出到数组,但是使用数组保存再进行reverse操作会降低空间复杂度
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
ListNode* cur=head;
while(cur) {
res.push_back(cur->val);
cur=cur->next;
}
reverse(res.begin(),res.end());
return res;
}
};