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
Prerequisite:
In this tutorial, we are writing Java program to reverse linked list. You can also check C++ code to reverse linked list.
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.