w3resource

C++ Linked List Exercises: 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:

C++ Exercises: Reverse linked list.

Test Data:
Original Linked list:
11 9 7 5 3 1
Reverse Linked list:
1 3 5 7 9 11

Sample Solution:

C++ Code:

#include <iostream>
 
using namespace std;
 
//Declare node 
struct node{
    int num;
    node *next;
};
 
//Starting (Head) node
struct node *head=NULL;
 
//Insert node at start
void insert_Node(int n){
    struct node *new_node=new node;
    new_node->num=n;
    new_node->next=head;
    head=new_node;
}
void reverse()
    {
        // Set the current, previous, and next pointers to their initial values
        node* current = head;
        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; 
   }
//Display all nodes
void display_all_nodes()
  {
	struct node *temp = head;
    while(temp!=NULL){
        cout<<temp->num<<" ";
        temp=temp->next;
    }
    cout<<endl;
}
 
int main(){
    insert_Node(1);
    insert_Node(3);
    insert_Node(5);
    insert_Node(7);
    insert_Node(9);
    insert_Node(11);
    cout<<"Original Linked list:\n";
	display_all_nodes();
	cout<<"\nReverse Linked list:\n";
    reverse();
    display_all_nodes();
    return 0;
}

Sample Output:

Original Linked list:
11 9 7 5 3 1 

Reverse Linked list:
1 3 5 7 9 11  

Flowchart:

Flowchart: Reverse linked list.
Flowchart: Reverse linked list.

CPP Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Create and display linked list.
Next C++ Exercise: Count number of nodes in a linked list.

What is the difficulty level of this exercise?



Share this Tutorial / Exercise on : Facebook and Twitter

C++ Programming: Tips of the Day

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

Ref: https://bit.ly/3niU71x