剑指 Offer(第2版)面试题 6:从尾到头打印链表
剑指 Offer(第2版)面试题 6:从尾到头打印链表
题目来源:17. 从尾到头打印链表
解法1:遍历
从头到尾遍历链表,将值插入数组,最后反转数组。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
vector<int> printListReversingly(ListNode *head)
{
if(head == nullptr)
return {};
ListNode *p = head;
vector<int> ans;
while (p)
{
ans.push_back(p->val);
p = p->next;
}
reverse(ans.begin(), ans.end());
return ans;
}
};
复杂度分析:
时间复杂度:O(n),其中 n 是链表的长度。
空间复杂度:O(1)。
解法2:递归
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
vector<int> printListReversingly(ListNode *head)
{
if(head == nullptr)
return {};
vector<int> ans;
helper(head, ans);
return ans;
}
// 辅函数 - 递归
void helper(ListNode *p, vector<int> &nums)
{
if (p == nullptr)
return;
if (p->next)
helper(p->next, nums);
nums.push_back(p->val);
}
};
复杂度分析:
时间复杂度:O(n),其中 n 是链表的长度。
空间复杂度:O(n),其中 n 是链表的长度。
解法3:栈
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
if(head == nullptr)
return {};
ListNode* p = head;
stack<int> s;
while(p)
{
s.push(p->val);
p = p->next;
}
vector<int> ans;
while(!s.empty())
{
ans.push_back(s.top());
s.pop();
}
return ans;
}
};
复杂度分析:
时间复杂度:O(n),其中 n 是链表的长度。
空间复杂度:O(n),其中 n 是链表的长度。