题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路
第一种方法:将链表翻转,然后从头进行打印链表的值
第二种方法:
- 遍历链表,并将链表的值存入到一个栈中
- 当栈不为空的时候,打印栈顶元素,弹出栈顶元素,直到栈为空
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> st;
ListNode *p = head;
while(p != nullptr){
st.push(p->val);
p = p->next;
}
vector<int> res;
while(!st.empty()){
res.push_back(st.top());
st.pop();
}
return res;
}
};