Search code examples
c++pointersreturn-typesingly-linked-list

Method to Reverse a Linked list in c++


I am writing a method to reverse a linked list in c++. I'm trying to use Node* instead of void return type but facing a number of errors.

My method code..

  Node* Reverse(Node *head)
   {
     struct node* prev   = NULL;
     struct node* current = head;
     struct node* next;
     while (current != NULL)
      {
        next  = current->next; 
        current->next = prev;  
        prev = current;
        current = next;
      }
        head = prev;
   }

The compile time error message i am receiving..

    solution.cc: In function 'Node* Reverse(Node*)':
    solution.cc:24:22: error: cannot convert 'Node*' to 'Reverse(Node*)::node*' in initialization
  node* current = head;
                  ^
    solution.cc:28:24: error: invalid use of incomplete type 'struct Reverse(Node*)::node'
     next  = current->next; 
                    ^
    solution.cc:23:14: error: forward declaration of 'struct Reverse(Node*)::node'
   struct node* prev   = NULL;
          ^
    solution.cc:29:16: error: invalid use of incomplete type 'struct Reverse(Node*)::node'
     current->next = prev;  
            ^
    solution.cc:23:14: error: forward declaration of 'struct Reverse(Node*)::node'
   struct node* prev   = NULL;
          ^
    solution.cc:33:10: error: cannot convert 'Reverse(Node*)::node*' to 'Node*' in assignment
 head = prev;
      ^
    solution.cc:34:1: error: no return statement in function returning non-void [-Werror=return-type]
   }
   ^
    cc1plus: some warnings being treated as errors

Solution

  • Node is not same as node and you are missing a return statement

    Node* Reverse(Node *head)
    {
     struct Node* prev   = NULL;
     struct Node* current = head;
     struct Node* next;
     while (current != NULL)
      {
        next  = current->next; 
        current->next = prev;  
        prev = current;
        current = next;
      }
        head = prev;
       return head;
    }