【问题标题】:No viable overload error in reversing a linked list反转链表时没有可行的重载错误
【发布时间】:2022-08-18 15:48:51
【问题描述】:

我正在尝试反转具有以下代码的linked list

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* current,prev,next;
        prev=NULL;
        current=head;
        while(current!=NULL){
            next=current->next;
            current->next=prev;
            prev=current;
            current=next;
        }
        head=prev;
        return head;
    }
};

对我来说一切都很好,但我遇到了错误没有可行的重载\'=\'下一个=当前->下一个

我很想知道,为什么会出现这个错误?亲切地寻求帮助

  • next 不是指针。 stackoverflow.com/a/3280765/920069
  • ListNode* current,prev,next; 中,只有current 是指向ListNode 的指针,其余都是ListNode 类型。使用ListNode *current, *prev, *next;
  • 接近一个错字。 ListNode* current,prev,next;ListNode* current; ListNode prev; ListNode next; 相同。你想要ListNode* current,*prev,*next;

标签: c++ data-structures linked-list


【解决方案1】:

改变

ListNode* current,prev,next;

ListNode *current, *prev, *next;

最好在第一次使用时声明它们,而不是之前

ListNode* reverseList(ListNode* head) {
    ListNode* prev=NULL;
    ListNode* current=head;
    while(current!=NULL){
        ListNode* next=current->next;
        current->next=prev;
        prev=current;
        current=next;
    }
    head=prev;
    return head;
}

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2018-03-01
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多