题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路
栈有先进后出的特点,用一个栈来作为过渡。将作为输入链表数据从头到尾压栈,再根据出栈的顺序放进结果链表中。
C++ push_back( )函数,将元素放在链表最后。
代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
stack<int> tmp;
ListNode* p = head;
while(p != NULL){
tmp.push(p->val);
p = p->next;
}
while(!tmp.empty()){
res.push_back(tmp.top());
tmp.pop();
}
return res;
}
};