How to Reverse a Linked List in Java?

A linked list is a kind of linear data structure. Each member of the list, called a “node,” points to the next element in the sequence. The advantage of this structure is that you can easily can add in or delete elements using iteration. In Java, we use the LinkedList class to create linked lists. The LinkedList class extends AbstractSequentialList and implements the List interface. Here’s how to reverse a linked list in Java:

Reversing a Linked List in Java

There are two methods you can use to reverse a linked list: iteration and recursion.

1. How to Reverse a Linked List in Java Using Iteration

In order to reverse a linked list in Java using iteration, you need to take three nodes at a time. Let’s called them the current node, the previous node, and the subsequent node. And we want to swap the order by:

  • storing the subsequent node;
  • making the current node the previous node;
  • moving the nodes up by 1 to get the reverse linked list (n+1).

Here is the basic code:

public void reverseList() {
Node currentnode = head;
Node previousnode = null;
Node subsequentnode = null;

while(currentnode != null) {
subsequentnode = currentnode.next; // store new node

currentnode.next = previousnode; // make the swap
previousnode = current; // n+1

current = subsequentnode; // n+1 for subsequent node
}

head = previousnode; // currentnode is null

}

2. How to Reverse a Linked List Using Recursion

This is another method that allows you to reverse a linked list, but uses the same basic concept. It is a kind of swap, except we are taking two nodes at a time and reversing the link between the nodes. In other words, we reverse the linked list by making the second node become the first one.

public static Node reverseLinkedList(Node node) {
if (node == null || node.next == null) {
return node;
}

Node subsequentnode = reverseLinkedList(node.next);
node.next.next = node;
node.next = null;
return subsequentnode;

Note: Since you’re here, you might also be interested in our collection of 20 Java interview questions & their answers.

Conclusion

These are the two basic methods to reverse a linked list. We can either use iteration, where we do what amounts to a swap, or we can reverse a linked list by using recursion, where we reverse the nodes in pairs.