普通
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
int arrSize=0;
vector<int> ans;
for(auto it=head;it!=NULL;it=it->next){
arrSize++;
}
ans.resize(arrSize);
int i=arrSize-1;
for(auto it=head;it!=NULL;it=it->next,i--){
ans[i]=it->val;
}
return ans;
}
};
❤递归
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
cnt=0;
dfs(head,0);
return ans;
}
private:
vector<int> ans;
int cnt;
void dfs(ListNode* head,int i){
if(head==NULL){
cnt=i;
ans.resize(cnt);
return;
}
dfs(head->next,i+1);
ans[cnt-i-1]=head->val; //此处一定要注意!
}
};