Reverse a Linked List In JAVA [Complete Code]

Reverse a Linked List In JAVA [Complete Code]

Problem statement: You have given a pointer to the head node of a linked list, the task is to reverse the linked list.

Example: 1->2->3->4->5->null
Output: 5->4->3->2->1->null
Reverse a Linked List in Java

Prerequisite:

  1. Basics of Java programming
  2. Understanding of the Linked List.
  3. Basic understanding of classes and objects in Java.
  4. Swapping

In this tutorial, we are writing Java program to reverse linked list. You can also check C++ code to reverse linked list.

[Solution] Reverse a Linked List In JAVA

import java.util.*;

class Main {
	public static class ListNode {
    	int val = 0;
    	ListNode next = null;

    	ListNode(int val) {
      		this.val = val;
    	}
	}

	// we will get each node data and from beginning to last 
	// and swap them with each other
	public static ListNode reverse(ListNode head) {
		ListNode n = head;
    	int size = 0;
    	while (n != null) {
        	size ++;
        	n = n.next;
    	}
    	int i = 0, j = size - 1;
    	while (i < j) {
        	ListNode a = getNode(i, head);
        	ListNode b = getNode(j, head);
        	int temp = a.val;
        	a.val = b.val;
        	b.val = temp;
        	i++;
        	j--;
    	}
    	return head;;
	}

	private static ListNode getNode(int indx, ListNode head) {
   		ListNode n = head;
   		if (indx == 0)
     		return head;
    	for (int i = 0; i < indx; i++) {
        	n = n.next;
    	}
    	return n;
	}

	public static void main(String[] args) {
    	Scanner scn = new Scanner(System.in);
    	int n = scn.nextInt();
    	ListNode dummy = new ListNode(-1);
    	ListNode prev = dummy;
    	while (n-- > 0) {
        	prev.next = new ListNode(scn.nextInt());
        	prev = prev.next;
    	}

    	ListNode head = reverse(dummy.next);
    	while (head != null) {
        	System.out.print(head.val + " ");
			head = head.next;
    	}
	}
}

As we are using Java basics syntax to implement this logic, it will work for any Java versions like Java 8, Java 12,…

You can implement this logic in C/C++ and python as well.

This is all about this tutorial to reverse a Linked List In JAVA. If you have any questions or point to discuss, let me know in the comment.

Leave a Reply

Your email address will not be published. Required fields are marked *