输入一个链表,按链表值从尾到头的顺序返回一个ArrayList
思路:
1、首先将链表中的值都压入栈中;
2、然后数据出栈赋值给数组;
3、最后输出数组
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ArrayList;
stack<int> stacknode;
ListNode* p=head;
//入栈
while(p!=NULL){
stacknode.push(p->val);
p=p->next;
}
//出栈,并存储在数组中
while(!stacknode.empty()){
ArrayList.push_back(stacknode.top());
stacknode.pop();
}
return ArrayList;
}
};