Program to create a singly linked list of n nodes and display it in reverse order

Explanation

In this program, we need to create a singly linked list and display the list in reverse order.

Original List

Program to create a singly linked list of n nodes and display it in reverse order

Reversed List

Program to create a singly linked list of n nodes and display it in reverse order

One of the approaches to solving this problem is to reach the end the of the list and display the nodes from tail to head recursively.

Algorithm

  1. Create a class Node which has two attributes: data and next. Next is a pointer to the next node in the list.
  2. Create another class which has two attributes: head and tail.
  3. addNode() will add a new node to the list:
    1. Create a new node.
    2. It first checks, whether the head is equal to null which means the list is empty.
    3. If the list is empty, both head and tail will point to the newly added node.
    4. If the list is not empty, the new node will be added to end of the list such that tail's next will point to the newly added node. This new node will become the new tail of the list.
  4. reverse() will reverse the order of the nodes present in the list.
    1. This method checks whether node next to current is null which implies that, current is pointing to tail, then it will print the data of the tail node.
    2. Recursively call reverse() by considering node next to current node and prints out all the nodes in reverse order starting from the tail.
  5. display() will display the nodes present in the list:
    1. Define a node current which will initially point to the head of the list.
    2. Traverse through the list till current points to null.
    3. Display each node by making current to point to node next to it in each iteration.

Solution

Python

Output:

Original List: 
1 2 3 4 
Reversed List: 
4 3 2 1 

C

Output:

Original List: 
1 2 3 4 
Reversed List: 
4 3 2 1 

JAVA

Output:

Original List: 
1 2 3 4 
Reversed List: 
4 3 2 1 

C#

Output:

Original List: 
1 2 3 4 
Reversed List: 
4 3 2 1 

PHP

Output:

Original List: 
1 2 3 4 
Reversed List: 
4 3 2 1 

Next Topic#




Latest Courses