1. 题目
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
2. Code
将节点的值保存到栈stack
中,最后从栈中弹出再保存到vector
中
递归的解法如果层数太多的时候会爆栈
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head){
ListNode* tmp = head;
stack<int> st;
vector<int> res;
while(tmp){
st.push(tmp->val);
tmp = tmp->next;
}
while(!st.empty()){
res.push_back(st.top());
st.pop();
}
return res;
}
};