题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
限制:0 <= 链表长度 <= 10000
解题过程遇到的问题:
1.如何找到链表的尾节点?
2.如何知道链表的长度?
题解:
1.递推法:
利用递归,先递推至链表末端;回溯时,依次将节点值加入列表,即可实现链表值的倒序输出。
复杂度分析:
时间复杂度 O(N)O(N): 遍历链表,递归 NN 次。
空间复杂度 O(N)O(N): 系统递归需要使用 O(N)O(N) 的栈空间。
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
recur(head);
return res;
}
private:
vector<int> res;
void recur(ListNode* head) {
if(head == nullptr) return;
recur(head->next);
res.push_back(head->val);
}
};
执行用时:4 ms
, 在所有 C++ 提交中击败了90.72%的用户
内存消耗:9 MB
, 在所有 C++ 提交中击败了27.28%的用户
2.栈
其实这种倒序输出,就是先进后出,我们就可以想到借助栈来执行。
算法流程:
入栈: 遍历链表,将各节点值 push 入栈。
出栈: 将各节点值 pop 出栈,存储于数组并返回。
复杂度分析:
时间复杂度 O(N)O(N): 入栈和出栈共使用 O(N)O(N) 时间。
空间复杂度 O(N)O(N): 辅助栈 stack 和数组 res 共使用 O(N)O(N) 的额外空间。
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<int> stk;
while(head != nullptr) {
stk.push(head->val);
head = head->next;
}
vector<int> res;
while(!stk.empty()) {
res.push_back(stk.top());
stk.pop();
}
return res;
}
};
题目题解来源:
https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5d8831/