Javatpoint Logo
Javatpoint Logo

Q. Program to create a circular linked list of n nodes and display it in reverse order.

Explanation

In this program, we create a circular linked list, then traverse the list in the reverse order and print the nodes.

Algorithm

  1. Define a Node class which represents a node in the list. It has two properties data and next which will point to the next node.
  2. Define another class for creating the circular linked list and it has two nodes: head and tail. It has two methods: add(), display() and reverse().
  3. add() will add a node to the list:
    1. It first checks whether the head is null, then it will insert the node as the head.
    2. Both head and tail will point to the newly added node.
    3. If the head is not null, the new node will be the new tail, and new tail will point to head as it is a circular linked list.
  4. display() will show all the nodes present in the list.
    1. Define a new node 'current' that will point to the head.
    2. Print current.data till current will points to head again.
    3. Current will point to the next node in the list in each iteration.
  5. reverse() will print the circular linked list in reverse order.
    1. This method checks whether next node to current is head 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.

Solution

Python

Output:

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

C

Output:

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

JAVA

Output:

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

C#

Output:

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

PHP

Output:

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

Next Topic#





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA