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(1);
  14. Node two = createNewNode(2);
  15. Node three = createNewNode(3);
  16. Node four = createNewNode(4);
  17.  
  18. head.next = two;
  19. two.next = three;
  20. three.next = four;
  21.  
  22. head.random = three;
  23. two.random = four;
  24.  
  25. Node clonedList = clone(head);
  26. Node current = clonedList;
  27. while(current != null)
  28. {
  29. System.out.println("val: "+ current.value );
  30. if( current.random != null)
  31. System.out.println(" random: " + current.random.value);
  32. current = current.next;
  33. }
  34. }
  35.  
  36. public static Node clone(Node head)
  37. {
  38. if( head == null )
  39. {
  40. return null;
  41. }
  42.  
  43. Node current = head;
  44. while( current != null)
  45. {
  46. Node temp = createNewNode(current.value);
  47. temp.next = current.next;
  48. current.next = temp;
  49. current = temp.next;
  50. }
  51.  
  52. Node clonedHead = head.next;
  53.  
  54. current = head;
  55. while( current != null )
  56. {
  57. if( current.random != null)
  58. {
  59. current.next.random = current.random.next;
  60. }
  61.  
  62. current = current.next.next;
  63. }
  64.  
  65. current = head;
  66. while( current != null )
  67. {
  68. Node temp = current.next;
  69. current.next = temp.next;
  70. current = current.next;
  71. if( current != null)
  72. {
  73. temp.next = current.next;
  74. }
  75. }
  76.  
  77. return clonedHead;
  78. }
  79.  
  80. public static Node createNewNode(int value)
  81. {
  82. Node node = new Node(value);
  83. return node;
  84. }
  85. }
  86.  
  87. class Node
  88. {
  89. int value;
  90. Node next;
  91. Node random;
  92.  
  93. public Node(int val)
  94. {
  95. value = val;
  96. }
  97. }
Success #stdin #stdout 0.11s 320256KB
stdin
Standard input is empty
stdout
val: 1
 random: 3
val: 2
 random: 4
val: 3
val: 4