题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
问题分析
- 可以通过栈的方式,将链表放入同时栈中。栈满足后进先出的数据特点
- 可以直接顺序打印后,将打印数字进行翻转
解题思路1
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> reverseList;
ListNode* Node = head;
stack<ListNode*> stackList;
if (head == nullptr)
{
return reverseList;
}
//放入栈中,注意不要少放元素
while (Node != NULL)
{
stackList.push(Node);
Node = Node->next;
}
//弹出
while (!stackList.empty())
{
ListNode* tmp = stackList.top();
reverseList.push_back(tmp->val);
stackList.pop();
}
return reverseList;
}
};
网友评论