题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路1:
借用栈,遍历链表,将链表的所有元素压入栈中,这样开始的元素在栈底,最后的元素在栈顶。再一个一个弹出,添加到res数组中。
代码如下:
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> elem;
vector<int> res;
ListNode* temp=head;
while(temp)
{
elem.push(temp->val);
temp=temp->next;
}
while(!elem.empty())
{
res.push_back(elem.top());
elem.pop();
}
return res;
}
};
思路二:
递归,到最后一个节点再添加元素。
代码如下:
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
if(head!=nullptr)
{
printListFromTailToHead(head->next);
res.push_back(head->val);
}
return res;
}
private:
vector<int> res;
};