编辑代码

#include <iostream>
#include <vector>

// 定义链表节点
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}  // 构造函数
};

// 递归函数
void reverseList(ListNode* head, std::vector<int>& result) {
    if (head == nullptr) {
        return;  // 递归终止条件
    }
    reverseList(head->next, result);  // 递归到下一个节点
    result.push_back(head->val);  // 将当前节点值加入结果
}

// 主函数
std::vector<int> reversePrint(ListNode* head) {
    std::vector<int> result;  // 用于存储逆序结果
    reverseList(head, result); // 递归处理
    return result;  // 返回结果数组
}

int main() {
    // 创建示例链表: 2 -> 3 -> 5
    ListNode* head = new ListNode(2);
    head->next = new ListNode(3);
    head->next->next = new ListNode(5);

    // 调用函数并获取结果
    std::vector<int> output = reversePrint(head);

    // 输出结果
    std::cout << "返回结果: [";
    for (size_t i = 0; i < output.size(); ++i) {
        std::cout << output[i];
        if (i < output.size() - 1) {
            std::cout << ", ";
        }
    }
    std::cout << "]" << std::endl;

    // 清理内存
    delete head->next->next;
    delete head->next;
    delete head;
    
    return 0;
}