题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路1
倒数打印,通过辅助栈来实现。
思路1代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> s; // 创建一个栈
while (head != nullptr){
s.push(head -> val);
head = head -> next;
}
int size = s.size();
std::vector<int> rlt(size);
int i;
for (i = 0; i < size; ++i){
rlt[i] = s.top();
s.pop();
}
return rlt;
}
};
思路2
递归。
思路2代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> res;
vector<int> printListFromTailToHead(ListNode* head) {
if (head != nullptr){
printListFromTailToHead(head->next);
res.push_back(head->val);
}
return res;
}
};