ofskuu 2025-01-24 21:14 采纳率: 71.4%
浏览 2
已结题

OJ链表逆置的代码报错

[Error] no matching function for call to 'ListNode::ListNode(const std::vector&)'
以下代码的报错

#include <iostream>
#include <vector>


struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};


ListNode* createList(const std::vector<int>& nums) {
    if (nums.empty()) return nullptr;
    
    ListNode* head = new ListNode(nums); 
    ListNode* current = head;
    for (size_t i = 1; i < nums.size(); ++i) {
        current->next = new ListNode(nums[i]);
        current = current->next;
    }
    return head;
}



ListNode* reverseList(ListNode* pHead) {
    ListNode* prev = nullptr;
    ListNode* curr = pHead;
    while (curr != nullptr) {
        ListNode* nextTemp = curr->next;
        curr->next = prev;
        prev = curr;
        curr = nextTemp;
    }
    return prev;
}


void printList(ListNode* head) {
    while (head != nullptr) {
        std::cout << head->val;
        if (head->next != nullptr) std::cout << " ";
        head = head->next;
    }
    std::cout << std::endl;
}


void deleteList(ListNode* head) {
    while (head != nullptr) {
        ListNode* temp = head;
        head = head->next;
        delete temp;
    }
}

int main() {
   
    std::vector<int> nums = {3, 7, 2, 5, 1, 4, 8, 9, 2};

    
    ListNode* head = createList(nums);

    
    std::cout << "Original List: ";
    printList(head);

    
    ListNode* reversedHead = reverseList(head);

    
    std::cout << "Reversed List: ";
    printList(reversedHead);

    
    deleteList(reversedHead);

    return 0;
}

  • 写回答

3条回答 默认 最新

  • 关注

    以下回复参考:皆我百晓生券券喵儿等免费微信小程序作答:

    你的问题在于createList函数中创建链表节点时使用了错误的构造函数。你定义了一个接受整数的构造函数,但是在创建链表头节点时使用了向量作为参数:

    ListNode* head = new ListNode(nums);
    

    这将引发错误,因为ListNode没有接受向量作为参数的构造函数。你应该将向量的每个元素作为单独的参数传递给ListNode的构造函数。你可以通过修改createList函数来解决这个问题。以下是修改后的代码:

    ListNode* createList(const std::vector<int>& nums) {
        if (nums.empty()) return nullptr;
        
        ListNode* head = new ListNode(nums[0]); // 使用向量的第一个元素作为参数创建头节点
        ListNode* current = head;
        for (size_t i = 1; i < nums.size(); ++i) {
            current->next = new ListNode(nums[i]); // 为每个元素创建一个新的节点并将其连接到当前节点后面
            current = current->next;
        }
        return head;
    }
    

    这样修改后,你的代码应该可以正常运行并输出原始链表和反转后的链表。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 2月1日
  • 已采纳回答 1月24日
  • 创建了问题 1月24日