题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
非递归解法
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> vec;
while (head)
{
vec.push_back(head->val);
head = head->next;
}
reverse(vec.begin(), vec.end());
return vec;
}
};
递归解法
对当前的head,求解reversePrint(head->next),再push_back head->val
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
if (!head)
return {};
auto vec = reversePrint(head->next);
vec.push_back(head->val);
return vec;
}
};

本文介绍了一种链表处理算法,即从尾到头逆序打印链表节点值的方法。提供了两种实现方案:非递归解法通过先遍历链表收集节点值,再反转数组完成;递归解法则直接利用递归特性,先处理子问题再解决当前问题。
249

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



