输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
//如果头节点为空,返回空vector,反之遍历链表把元素压入栈中,最后判断栈不为空时弹出栈元素并将元素插入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> ret;
if(head == nullptr)
{
return ret;
}
stack<int> count;
while(head != nullptr)
{
count.push(head->val);
head = head -> next;
}
while(!count.empty())
{
ret.push_back(count.top());
count.pop();
}
return ret;
}
};