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 ""+data;
  13. }
  14. }
  15.  
  16. /**
  17.  * Add Numbers
  18.  * @author Prateek
  19.  */
  20. class AddLists {
  21.  
  22. /**
  23. * Procedure to calulate resultant list
  24. * @param head1: head of 1st list
  25. * @param head2: head of 2st list
  26. * @return
  27. */
  28. public Node addLists(Node head1 , Node head2)
  29. {
  30. int sum1 = addition(head1,0); //sum of 1st list
  31. int sum2 = addition(head2,0); //sum of 2nd list
  32. return createList(sum1 + sum2);
  33. }
  34.  
  35. /**
  36. * Adds all the elements in the list
  37. * @return added sum
  38. */
  39. public int addition(Node head ,int sum){
  40. if(head==null)
  41. return sum;
  42.  
  43. sum = sum*10 + head.data;
  44. return addition(head.next , sum) ;
  45. }
  46.  
  47. /**
  48. * Creating list of the total sum Obtained
  49. * @param totSum is sum of the two list obtained
  50. * @return head of the new list created
  51. */
  52. public Node createList(int totSum){
  53. Node head=null;
  54.  
  55. while(totSum > 0){
  56. int val =totSum%10 ;
  57. totSum = totSum/10;
  58. head=insert(val,head);
  59. }
  60.  
  61. return head;
  62. }
  63.  
  64. /**
  65. * Inserts node at the beggining
  66. * @return head of the list
  67. */
  68. public Node insert(int val , Node head){
  69. Node node= new Node(val);
  70.  
  71. if(head==null)
  72. head=node;
  73. else
  74. {
  75. node.next = head;
  76. head=node;
  77. }
  78. return head;
  79. }
  80.  
  81.  
  82. /**
  83. * Prints the new list created
  84. * @param head
  85. */
  86. public void displayList(Node head)
  87. {
  88. Node tempNode;
  89. tempNode=head;
  90. while(tempNode!=null)
  91. {
  92. System.out.print(tempNode.data+"-->");
  93. tempNode=tempNode.next;
  94. }
  95. System.out.print("null");
  96. System.out.println();
  97. }
  98.  
  99. public static void main(String[] args) {
  100. Node head1=new Node(5);
  101. head1.next= new Node(3);
  102. head1.next.next= new Node(7);
  103. head1.next.next.next= new Node(6);
  104.  
  105.  
  106. Node head2=new Node(9);
  107. head2.next= new Node(4);
  108. head2.next.next= new Node(7);
  109. head2.next.next.next= new Node(2);
  110.  
  111.  
  112. AddLists obj=new AddLists();
  113. Node sumList= obj.addLists(head1, head2);
  114. obj.displayList(sumList);
  115. }
  116. }
  117.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
1-->4-->8-->4-->8-->null