Java Exercises: Reverse a given linked list

Java Basic: Exercise-121 with Solution

Write a Java program to reverse a given linked list.
Example: For linked list 20->40->60->80, the reversed linked list is 80->60->40->20

Pictorial Presentation:

Java Exercises: Reverse a given linked list

Sample Solution:

Java Code:

class LinkedList {

	static Node head;

	static class Node {

		int data;
		Node next_node;

		Node(int d) {
			data = d;
			next_node = null;

	/* Reverse the linked list */
	Node reverse(Node node) {
		Node prev_node = null;
		Node current_node = node;
		Node next_node = null;
		while (current_node != null) {
			next_node = current_node.next_node;
			current_node.next_node = prev_node;
			prev_node = current_node;
			current_node = next_node;
		node = prev_node;
		return node;

	// Prints the elements of the double linked list
	void printList(Node node) {
		while (node != null) {
			System.out.print(node.data + " ");
			node = node.next_node;

	public static void main(String[] args) {
		LinkedList list = new LinkedList();
		list.head = new Node(20);
		list.head.next_node = new Node(40);
		list.head.next_node.next_node = new Node(60);
		list.head.next_node.next_node.next_node = new Node(80);
		System.out.println("Original Linked list:");
		head = list.reverse(head);
		System.out.println("Reversed Linked list:");

Sample Output:

Original Linked list:
20 40 60 80 
Reversed Linked list:
80 60 40 20 


Flowchart: Java exercises: Reverse a given linked list

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program that searches a value in an m x n matrix.
Next: Write a Java program to find a contiguous subarray with largest sum from a given array of integers.

What is the difficulty level of this exercise?

Java: Tips of the Day

Execution of console commands:

Java allows you to execute console commands directly from code using a class Runtime. It is very important not to forget about exception handling.

For example, let's try to open a PDF file through a Java terminal:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ShellCommandExec {
  public static void main(String[] args) {
    String gnomeOpenCommand = "gnome-open //home//user//Documents//MyDoc.pdf";
    try {
      Runtime rt = Runtime.getRuntime();
      Process processObj = rt.exec(gnomeOpenCommand);
      InputStream stdin = processObj.getErrorStream();
      InputStreamReader isr = new InputStreamReader(stdin);
      BufferedReader br = new BufferedReader(isr);
      String myoutput = "";
      while ((myoutput=br.readLine()) != null) {
        myoutput = myoutput+"\n";
    catch (Exception e) {