题目描述
输入一个链表,按链表值从尾到头的顺序返回一个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> res;
if (!head) return res;
if (!head->next) {res.push_back(head->val); return res;}
//方法1:反转链表
/*ListNode *new_head=nullptr;
ListNode *temp=nullptr;
while(head){
temp=head->next;
head->next=new_head;
new_head=head;
head=temp;
}
//保存节点数据
while(new_head){
res.push_back(new_head->val);
new_head=new_head->next;
}*/
//方法2:用栈
stack<int> p;
while(head){
p.push(head->val);
head=head->next;
}
while(!p.empty()){
res.push_back(p.top());
p.pop();
}
return res;
}
};