fork download
  1. class Node {
  2.  
  3. public Node prev;
  4. public int data;
  5. public Node next;
  6.  
  7. public Node(int data) {
  8. this.data=data;
  9. }
  10.  
  11. public String toString(){
  12. return ""+this.data ;
  13. }
  14. }
  15. /**
  16.  * Reverse Linked List(recursively)
  17.  * @author Prateek
  18.  */
  19. class ReverseList {
  20.  
  21. /**
  22. * Reverse Linked List (recursively)
  23. * @param head
  24. * @return
  25. */
  26. public Node reverse(Node head){
  27. Node revHead ; // to store the new Head pointer
  28.  
  29. if( head== null || head.next==null )
  30. return head;
  31.  
  32. revHead=reverse(head.next) ;
  33.  
  34. head.next.next = head; // points to itself to create loop
  35. head.next = null; // breaks the loop (old link)
  36.  
  37. return revHead ;
  38. }
  39.  
  40. public static void main(String[] args) {
  41. // 1 -> 2 - > 3 -> 4 -> NUll
  42. ReverseList obj = new ReverseList() ;
  43. Node root = new Node(1) ;
  44. root.next =new Node(2) ;
  45. root.next.next =new Node(3) ;
  46. root.next.next.next =new Node(4) ;
  47.  
  48. System.out.println("Original List :");
  49. obj.display(root);
  50.  
  51. System.out.println("\n\nReversed List :");
  52. obj.display(obj.reverse(root)) ;
  53.  
  54. }
  55.  
  56. private void display(Node head) {
  57. Node temp = head ;
  58. while(temp!=null) {
  59. System.out.print(temp + "\t");
  60. temp=temp.next ;
  61. }
  62. }
  63. }
  64.  
Success #stdin #stdout 0.06s 381184KB
stdin
Standard input is empty
stdout
Original List :
1	2	3	4	

Reversed List :
4	3	2	1