Zhorzh

Untitled

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