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?



Follow us on Facebook and Twitter for latest update.

C++ Programming: Tips of the Day

Function for C++ struct

A struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template)

Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.

struct foo {
int bar;
foo() : bar(3) {}   //look, a constructor
intgetBar() 
  { 
return bar; 
  }
};

foo f;
int y = f.getBar(); // y is 3

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

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook