Reverse a linked list in Java using recursion

In this article, we will write a java program to reverse a singly linked list using recursion.

Program:

Here is the recursive method to reverse a linked list :

//reverse using Recursion private Node reverse[Node head] { if[head==null || head.next == null] return head; Node p = reverse[head.next]; head.next.next = head;//n+1 th node pointing nth node head.next = null; return p; }


Here is complete implementation of Linked List along with the reverse method :

package com.topjavatutorial; public class LinkedList { private Node top; private static class Node { private int value; private Node next; Node[int value] { this.value = value; } } private void addToEnd[Node n]{ if[top == null] top = n; else{ Node temp = top; while[temp.next != null] temp = temp.next; temp.next = n; } } public static void main[String[] args] { LinkedList list = new LinkedList[]; Node top = new Node[30]; list.addToEnd[top]; list.addToEnd[new Node[10]]; list.addToEnd[new Node[5]]; list.addToEnd[new Node[23]]; list.addToEnd[new Node[20]]; System.out.println["Printing nodes in current order"]; list.printList[top]; System.out.println["\n\nPrinting nodes in reverse order"]; Node n = list.reverse[top]; list.printList[n]; } public void printList[Node top]{ while[top != null]{ System.out.printf["%d ", top.value]; top = top.next; } } //reverse using Recursion private Node reverse[Node head] { if[head==null || head.next == null] return head; Node p = reverse[head.next]; head.next.next = head;//n+1 th node pointing nth node head.next = null; return p; } }


Output :


Printing nodes in current order
30 10 5 23 20

Printing nodes in reverse order
20 23 5 10 30


© 2016 2018, . All rights reserved. On republishing this post, you must provide link to original post

Share this article :

  • Click to share on LinkedIn [Opens in new window]
  • Click to share on Facebook [Opens in new window]
  • Click to share on Twitter [Opens in new window]
  • More
  • Click to share on Pinterest [Opens in new window]
  • Click to share on Flipboard [Opens in new window]
  • Click to share on Tumblr [Opens in new window]
  • Click to share on Reddit [Opens in new window]
  • Click to share on Pocket [Opens in new window]

Related

Popular Articles you may like :

  • Java 8 Interview Questions
  • RESTful CRUD operations using Jersey and Hibernate
  • Frequently asked Java Programming Interview questions on Strings

Video liên quan

Chủ Đề