题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
代码实现
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> result;
stack<int> arr;
ListNode* p=head;
while(p!=NULL){
arr.push(p->val);//push()进栈函数
p=p->next;
}
int len=arr.size();
for (int i=0;i<len;i++){
result.push_back(arr.top());//top()取栈顶元素;
//vector头文件里面就有push_back函数,作用为在vector尾部加入一个数据。
arr.pop();//pop()弹出栈顶元素
}
return result;
}
};