编辑代码

#include <iostream>
#include <vector>
#include <stack>

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

// 主函数
std::vector<int> reversePrint(ListNode* head) {
    std::stack<int> s;  // 使用栈来存储节点值
    std::vector<int> result;

    // 遍历链表,将节点值压入栈
    ListNode* current = head;
    while (current != nullptr) {
        s.push(current->val);
        current = current->next;
    }

    // 弹出栈中的元素并存入结果数组
    while (!s.empty()) {
        result.push_back(s.top());
        s.pop();
    }

    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;
}