Reverse a linked list. (Using recursion)

Reverse a linked list using recursion using Java.

Solution:

public class Node {

int data;
Node next;

public Node(int a, Node next)
{
this.data= a;
this.next = next;
}

}

public class Linkedlist {
public static void main(String[] args) {
// TODO Auto-generated method stub
Node node1= new Node(1,null);
Node node2= new Node(2, null);
Node node3= new Node(3, null);
node1.next=node2;
node2.next=node3;
node3.next=null;
printlist(node1);
System.out.println("\n*********");
printreverse(node1);
}

public static void printlist(Node n) 
{
if(n!=null)
{
System.out.print(" " + n.data);//will print in order
printlist(n.next);
}
}
public static void printreverse(Node n)
{
if(n!=null)
{
printreverse(n.next);
                         // will stack the nested calls and return the output in reverse order
//as per stack property calls will be stacked and the last one will be returned first
System.out.print(" "+n.data);
}
}
}

Comments

Popular posts from this blog

Priority Scheduling Algorithm Java Program.

Implement UNIX system calls like ps, fork, join, exec family, and wait for process management (use shell script/ Java/ C programming).

Implement a class CppArray which is identical to a one-dimensional C++ array (i.e., the index set is a set of consecutive integers starting at 0) except for the following : 1. It performs range checking. 2.It allows one to be assigned to another array through the use of assignment operator. 3.It supports a function that returns the size of the array.