Zhorzh

Untitled

Mar 11th, 2022
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. let input = [
  2. '7 4',
  3. '1 5 4 7',
  4. ]
  5.  
  6. let print = this.print || console.log;
  7. let gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
  8. const arr1 = gets().split(' ').map(Number);
  9. const arr2 = gets().split(' ').map(Number);
  10. const n = arr1[0];
  11. const k = arr1[1];
  12. const testMap = new Map();
  13. class LinkedListNode {
  14. constructor(value) {
  15. this.value = value;
  16. this.next = null;
  17. this.prev = null;
  18. }
  19. }
  20. class DoublyLinkedList {
  21. constructor(){
  22. this.head = null;
  23. this.tail = null;
  24. }
  25.  
  26. addLast(value) {
  27. const newNode = new LinkedListNode(value)
  28. if (!this.head) {
  29. this.tail = newNode;
  30. this.head = newNode;
  31. } else {
  32. this.tail.next = newNode;
  33. newNode.prev = this.tail;
  34. this.tail = newNode;
  35. }
  36. }
  37. insertAfter(node, nextNode) {
  38. if (!node.next) {
  39. node.next = nextNode;
  40. nextNode.prev = node;
  41. nextNode.next = null;
  42. this.tail = nextNode;
  43. }
  44. else {
  45.  
  46. nextNode.next = node.next;
  47. nextNode.prev = node;
  48. node.next = nextNode;
  49. nextNode.next.prev = nextNode;
  50. }
  51. }
  52. find(value) {
  53. let current = this.head;
  54. while (current !== null) {
  55. if (current.value === value) {
  56. return current;
  57. }
  58. current = current.next;
  59. }
  60. return null;
  61. }
  62. values() {
  63. const values = [];
  64. let current = this.head;
  65. while (current !== null) {
  66. values.push(current.value);
  67. current = current.next;
  68. }
  69. return values;
  70. }
  71. remove(node) {
  72. if (node.prev === null) {
  73. this.head = node.next;
  74. this.head.prev = null;
  75. } else if (node.next === null) {
  76. this.tail = node.prev;
  77. this.tail.next = null;
  78. } else {
  79. node.prev.next = node.next;
  80. node.next.prev = node.prev;
  81. }
  82. return node
  83. }
  84. }
  85. const linkedList = new DoublyLinkedList();
  86. for (let i = 1; i<= n; i++) {
  87. linkedList.addLast(i);
  88. testMap.set(i, linkedList.find(i));
  89. }
  90. for(let i = 0; i< k; i++) {
  91. const currentNode = testMap.get(arr2[i])
  92. let final = 0;
  93. currentNode.value %2 ===0 ? final = currentNode.value / 2 : final = currentNode.value * 2;
  94. if( final > n ) {
  95. final = n
  96. }
  97. if ( currentNode.value === final) {
  98. continue;
  99. }
  100. const nodeNext = testMap.get(final);
  101. const removeD = linkedList.remove(currentNode);
  102. linkedList.insertAfter(nodeNext, removeD);
  103. }
  104. print(linkedList.values().join(' '))
  105.  
Advertisement
Add Comment
Please, Sign In to add comment