题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
解法
解法一:利用STL自带的容器栈
思路:创建一个堆栈对象,从头遍历链表,依次把元素压入堆栈当中。然后依次获取栈顶元素,push到vector数组里面,再出栈。重复上述过程直至栈为空。时间复杂度:O(N)。
代码:
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
stack<int> s;
vector<int> a;
struct ListNode *temp=head;
while(temp!=NULL)
{
s.push(temp->val);
temp=temp->next;
}
while(!s.empty())
{
int num=s.top();//注意这里是s.top(),若写成s.pop()会报错
a.push_back(num);
s.pop();
}
return a;
}
};
解法二:直接从头遍历push到vector,最后用reverse()函数倒置vector即可
时间复杂度:O(N)。
代码:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> a;
while(head!=NULL)
{
a.push_back(head->val);
head=head->next;
}
reverse(a.begin(),a.end()); //就很简单
return a;
}
};
解法三:倒置链表
创建两个临时指针,指向一前一后,时间复杂度O(N)。

代码:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> a;
struct ListNode *first=NULL,*second=NULL;
while(head)
{
second=head->next;
head->next=first;
first=head;
head=second;
}
while(first)
{
a.push_back(first->val);
first=first->next;
}
return a;
}
};
本文介绍三种链表逆序输出的方法:使用栈、直接遍历并反转vector、链表倒置。每种方法均有详细解析及代码实现,帮助读者深入理解链表操作。
2027

被折叠的 条评论
为什么被折叠?



