# 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->nullOutput: 5->4->3->2->1->null`

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) {
int size = 0;
while (n != null) {
size ++;
n = n.next;
}
int i = 0, j = size - 1;
while (i < j) {
int temp = a.val;
a.val = b.val;
b.val = temp;
i++;
j--;
}
}

private static ListNode getNode(int indx, ListNode head) {
if (indx == 0)
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;
}