fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // create LL
  13. Node head = createNewNode(9);
  14. Node two = createNewNode(0);
  15. Node three = createNewNode(0);
  16. Node nine = createNewNode(9);
  17.  
  18. head.next = two;
  19. two.next = three;
  20. three.next = nine;
  21.  
  22. Node reversedHead = reverseLL(head);
  23. printLL(reversedHead);
  24. incrementLL(reversedHead);
  25. Node normal = reverseLL(reversedHead);
  26. printLL(normal);
  27. }
  28.  
  29. public static void incrementLL(Node head)
  30. {
  31. Node current = head;
  32. Node previous = current;
  33. int carry = 1;
  34.  
  35. while( current != null && carry > 0 )
  36. {
  37. int temp = current.value;
  38.  
  39. temp += carry;
  40. carry = temp / 10;
  41. temp %= 10;
  42.  
  43. current.value = temp;
  44. previous = current;
  45. current = current.next;
  46. }
  47.  
  48. if( carry > 0 )
  49. {
  50. Node last = createNewNode(carry);
  51. previous.next = last;
  52. }
  53.  
  54. }
  55.  
  56. public static void printLL(Node head)
  57. {
  58. Node current = head;
  59. while( current != null)
  60. {
  61. System.out.println("value is :" + current.value);
  62. current = current.next;
  63. }
  64. System.out.println("-------");
  65. }
  66.  
  67. public static Node reverseLL(Node head)
  68. {
  69. Node current = head;
  70. Node previous = null;
  71.  
  72. while( current != null )
  73. {
  74. Node temp = current.next;
  75.  
  76. current.next = previous;
  77. previous = current;
  78. current = temp;
  79. }
  80.  
  81. return previous;
  82. }
  83.  
  84. public static Node createNewNode(int value)
  85. {
  86. Node node = new Node(value);
  87. return node;
  88. }
  89. }
  90.  
  91. class Node
  92. {
  93. int value;
  94. Node next;
  95.  
  96. public Node(int val)
  97. {
  98. value = val;
  99. }
  100. }
Success #stdin #stdout 0.1s 320320KB
stdin
Standard input is empty
stdout
value is :9
value is :0
value is :0
value is :9
-------
value is :9
value is :0
value is :1
value is :0
-------