https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
思路一:顺序存储后反向一下再返回即可。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> vec;
while(head)
vec.push_back(head->val),head=head->next;
reverse(vec.begin(),vec.end());
return vec;
}
};
思路二:利用递归(用栈也可以)。
/**
* 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> &vec,ListNode* head){
if(head){
dfs(vec,head->next);
vec.push_back(head->val);
}
}
vector<int> reversePrint(ListNode* head) {
vector<int> vec;
dfs(vec,head);
return vec;
}
};