Idea: This
question is very simple, you can use dfs to do it, or you can flip the linked list and do it later, just look at the code.
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void dfs(vector<int>& ans,ListNode* head){
if(head==NULL) return ;
dfs(ans,head->next);
ans.push_back(head->val);
return ;
}
vector<int> reversePrint(ListNode* head) {
vector<int> ans;
dfs(ans,head);
return ans;
}
};