Reversing a Linked List in Java

Reversing a linked list in java. In this program, it will print the node elements in the reverse order using singly linked list. The linked list class in Java is an ordered collection of objects that are all of the same type. A Linked List stores data in a series of containers. Each container includes a link to the next one in the sequence, and the list contains a reference to the first container.

public class Main 
{
class Node
{
int data;
Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
public Node first = null;
public Node last = null;
public void addNode(int data)
{
Node newNode = new Node(data);
if(first == null)
{
first = newNode;
last = newNode;
}
else
{
last.next = newNode;
last = newNode;
}
}
public void reverse(Node current)
{
if(first == null)
{
System.out.println("list is empty");
return;
}
else
{

if(current.next == null)
{
System.out.print(current.data + " ");
return;
}
reverse(current.next);
System.out.print(current.data + " ");
}
}
public void display()
{
Node current = first;
if(first == null)
{
System.out.println("list is empty");
return;
}
while(current != null)
{
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}

public static void main(String[] args)
{
Main sList = new Main();
sList.addNode(2);
sList.addNode(4);
sList.addNode(6);
sList.addNode(8);
sList.display();
System.out.println("Reversed List");
sList.reverse(sList.first);
}
}

 

Output:

2 4 6 8
Reversed List
8 6 4 2

Singly Linked List in Java Program

A single linked list is a linear data structure in which each list member contains a pointer to the next element in the list. A node is a single element in a singly linked list. The list’s first node is known as the head, while the list’s last node is known as the tail. 

A singly linked list is a sort of unidirectional linked list that may only be traversed in one direction, from head to final node. A node is the name for each element in a linked list. A single node contains data as well as a pointer to the next node, which aids in the list’s structure.

Node to Execute Reversing a Linked List in Java

A node is made up of two sections or sub-elements. The element is stored in a data part, while the link to the next node is stored in a next part. A linked list is a collection of related items. When many of these nodes are joined together to form a chain, the result is a linked list. Each node in the order points to the next node.

Display() Function in Linked List

The nodes in the list will be displayed using display(): Create a node current that points to the top of the list at first. Traverse the list until the current value is nil. In each cycle, make current point to the node next to it to display each node.