-1

I'm trying to reverse a linked list, which has the below code.

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

Everything looks fine to me but i'm getting error as no viable overloaded '=' next=current->next

I'm curious to know, why this error is coming out to be? kindly looking for help

  • 3
    `next` is not a pointer. https://stackoverflow.com/a/3280765/920069 – Retired Ninja Aug 18 '22 at 07:47
  • In `ListNode* current,prev,next;`, only `current` is a pointer to `ListNode` rest all are of type `ListNode`. Use `ListNode *current, *prev, *next;`. – Aamir Aug 18 '22 at 07:48
  • 2
    Close to a typo. `ListNode* current,prev,next;` is the same as `ListNode* current; ListNode prev; ListNode next;`. You want `ListNode* current,*prev,*next;` – Serge Ballesta Aug 18 '22 at 07:49
  • 1
    I recommend to follow the C++ Core Guidelines [ES.10: Declare one name (only) per declaration](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-name-one) – jabaa Aug 18 '22 at 07:49

1 Answers1

3

next and prev are not pointers. To make them pointers you need to specify * for each variable.

Change

ListNode* current,prev,next;

to

ListNode *current, *prev, *next;

Even better, declare variables when you first use them, not before

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;
}
john
  • 85,011
  • 4
  • 57
  • 81