﻿ C++ - Reverse linked list

## C++ Linked List: Exercise-2 with Solution

Write a C++ program to create a singly linked list of n nodes and display it in reverse order.

Visualization:

Test Data:
11 9 7 5 3 1
1 3 5 7 9 11

Sample Solution:

C++ Code:

``````#include <iostream> // Including input-output stream header file

using namespace std; // Using standard namespace

//Declare node
struct node{
int num; // Data field to store a number
node *next; // Pointer to the next node
};

//Insert node at start
void insert_Node(int n){
struct node *new_node=new node; // Creating a new node
new_node->num=n; // Assigning data to the new node
}

// Function to reverse the linked list
void reverse() {
// Set the current, previous, and next pointers to their initial values
node *prev = NULL, *next = NULL;

while (current != NULL) {
// Store next
next = current->next;
// Reverse the node pointer for the current node
current->next = prev;
// Advance the pointer one position.
prev = current;
current = next;
}
head = prev; // Make the last node (prev) as the new head of the reversed list
}

//Display all nodes
void display_all_nodes() {
struct node *temp = head; // Temporary node to traverse the list
while(temp != NULL) { // Loop to iterate through the list
cout << temp->num << " "; // Displaying the data in the current node
temp = temp->next; // Moving to the next node
}
cout << endl; // Displaying newline after printing all nodes
}

int main(){
insert_Node(1); // Inserting a node with value 1
insert_Node(3); // Inserting a node with value 3
insert_Node(5); // Inserting a node with value 5
insert_Node(7); // Inserting a node with value 7
insert_Node(9); // Inserting a node with value 9
insert_Node(11); // Inserting a node with value 11

display_all_nodes(); // Displaying all nodes in the original list

reverse(); // Reversing the linked list
display_all_nodes(); // Displaying all nodes in the reversed list

return 0; // Returning from the main function
}
``````

Sample Output:

```Original Linked list:
11 9 7 5 3 1

1 3 5 7 9 11
```

Flowchart:

CPP Code Editor: