Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. class Node {
  2. constructor(value=0, next = null, random = null) {
  3. this.value = value;
  4. this.next = next;
  5. this.random = random;
  6. }
  7. }
  8.  
  9. function clone(node) {
  10. if(node === null) return node;
  11. let current = node;
  12.  
  13. //copy every node and insert to list
  14. while(current !== null) {
  15. let copy = new Node(current.value);
  16. copy.next = current.next;
  17. current.next = copy;
  18. current = copy.next;
  19. }
  20.  
  21. //copy random pointer for each new node
  22. current = node;
  23. while(current !== null) {
  24. if(current.random !== null) {
  25. current.next.random = current.random.next;
  26. }
  27. current = current.next.next;
  28. }
  29.  
  30. //break list into two
  31. current = node;
  32. let newHead = node.next;
  33. while(current !== null) {
  34. let temp = current.next;
  35. current.next = temp.next;
  36. if(temp.next !== null) {
  37. temp.next = temp.next.next;
  38. }
  39. current = current.next;
  40. }
  41.  
  42. return newHead;
  43. }
  44.  
  45. //Using Map
  46. function clone(node) {
  47. if(node === null) return node;
  48.  
  49. let map = new Map();
  50. let copy = new Node(node.value);
  51. let current = node;
  52. let newHead = copy;
  53.  
  54. map.set(current, copy);
  55.  
  56. current = current.next;
  57. while(current !== null) {
  58. let temp = new Node(current.value);
  59. map.set(current, temp);
  60. copy.next = temp;
  61. copy = temp;
  62. current = current.next;
  63. }
  64.  
  65. current = node;
  66. copy = newHead;
  67.  
  68. while(current !== null) {
  69. if(current.randome !== null) {
  70. copy.random = map.get(current.random);
  71. } else {
  72. copy.random = null;
  73. }
  74.  
  75. current = current.next;
  76. copy = copy.next;
  77. }
  78.  
  79. return newHead;
  80. }
  81.  
  82. function print(node) {
  83. while(node !== null) {
  84. console.log(node.value + '=>' + node.random.value);
  85. node = node.next;
  86. }
  87. }
  88.  
  89. let node1 = new Node(1);
  90. let node2 = new Node(2);
  91. let node3 = new Node(3);
  92.  
  93. node1.next = node2;
  94. node2.next = node3;
  95. node3.next = null;
  96. node1.random = node2;
  97. node2.random = node2;
  98. node3.random = node1;
  99.  
  100. print(clone(node1));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement