题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路
将链表的val存到stack里,在输出到vector里面。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> vec;
vec.clear();
if(head == NULL)
return vec;
std::stack<int> s;
while(head != NULL)
{
s.push(head->val);
head = head->next;
}
while(!s.empty())//注意栈的循环条件
{
vec.push_back(s.top());
s.pop();
}
return vec;
}
};