Reverse a linked list without changing links between nodes (Data reverse only) in C++

Reverse a linked list without changing links between nodes (Data reverse only)

Here, in this page we will discuss Reverse a linked list without changing links between nodes in C++. We create a vector and store the elements of the linked list and them change the linked list node data by iterating the vector in reverse manner.

Reverse a linked list without changing the links

Algorithm :

  • Create a node say current and set it to head.
  • Now, Create a vector to store the node value in it. We will iterate over all nodes of linked list and push the current node data in vector and set current to next node. Repeat this till the current node does not become  NULL.
  • Now, again set current to head and take a variable say j and set it to vector.size()-1.
  • Now, change the current node data with vector[j] and decrement the j and set current to next node. Repeat this till current node does not become NULL.
  • In this way we can Reverse a linked list without changing links between nodes in C++
reverse a linked list without changing the links in C++

Code in C++ based on above approach

Run

#include<bits/stdc++.h>
using namespace std;
 
/* Link list node */
struct Node {
    int data;
    struct Node* next;
    Node(int data)
    {
        this->data = data;
        next = NULL;
    }
};
 
struct LinkedList {
    Node* head;
    LinkedList() { head = NULL; }
 
    /* Function to reverse the linked list */
    void reverse()
    {
        
        Node* current = head;
       
        std::vector<int> element ;
 
        while (current != NULL) {
            element.push_back(current->data);
            current = current->next;
         }
         
        
         current = head;
         int i=element.size()-1;
         
        while (current != NULL) {
            current->data = element[i--];
            current = current->next;
         } 
        
    }
 
   /* Function to print linked list */
  
    void print()
    {
        struct Node* temp = head;
        while (temp != NULL) {
            cout << temp->data << " "; temp = temp->next;
        }
    }
 
    void push(int data)
    {
        Node* temp = new Node(data);
        temp->next = head;
        head = temp;
    }
};
 
/* Driver code*/
int main()
{
   
    LinkedList ll;
    ll.push(10);
    ll.push(20);
    ll.push(30);
    ll.push(40);
 
    cout << "Given linked list\n";
    ll.print();
 
    ll.reverse();
 
    cout << "\nReversed Linked list \n";
    ll.print();
    return 0;
}

Output :

Given linked list 
40 30 20 10
Reversed Linked list
10 20 30 40