Site icon

Print single linked list in a reverse order (java / example / recursive)

Example: reverse single linked list using recursive algorithm

Fig 1: Print linked list in reverse order

 

Algorithm – print single linked list in reverse order using recursion

Time complexity of algorithm is O (n)

Program – print single linked list in reverse order using recursive algorithm.

1.) PrintReverseLinkedList Class:

package org.learn.Question;

import org.learn.List.Node;

public class PrintReverseLinkedList {
	public static void printReverseLinkedList(Node head) {
		if (null == head) {
			return;
		}
		printReverseLinkedList(head.next);
		System.out.printf("%d ", head.data);
	}

	public static void insert(Node head, int data) {
		while (head.next != null)
			head = head.next;
		head.next = new Node(data);
	}

	public static void print(Node head) {
		while (head != null) {
			System.out.printf("%d ", head.data);
			head = head.next;
		}
		System.out.println("");
	}
}

2.) App Class:

We are performing the following operation in main method

package org.learn.Client;

import org.learn.List.Node;
import org.learn.Question.PrintReverseLinkedList;

public class App {
	public static void main(String[] args) {
		int[] data = { 1, 2, 3, 4, 5 };
		Node head = new Node(data[0]);

		for (int count = 1; count < data.length; count++)
			PrintReverseLinkedList.insert(head, data[count]);

		System.out.println("1. Original Single linked list : ");
		PrintReverseLinkedList.print(head);

		System.out.println("2. Printing single linked list in reverse order : ");
		PrintReverseLinkedList.printReverseLinkedList(head);
	}
}

3.) Node Class:

package org.learn.List;

public class Node {
	public int data;
	public Node next;

	public Node(int num) {
		this.data = num;
		this.next = null;
	}
}

Output – print single linked list in reverse order using recursive algorithm

1. Original Single linked list : 
1 2 3 4 5 
2. Printing single linked list in reverse order : 
5 4 3 2 1 

Download code – print single linked list in reverse order

 

Exit mobile version