Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let input = [
- '7 4',
- '1 5 4 7',
- ]
- let print = this.print || console.log;
- let gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
- const arr1 = gets().split(' ').map(Number);
- const arr2 = gets().split(' ').map(Number);
- const n = arr1[0];
- const k = arr1[1];
- const testMap = new Map();
- class LinkedListNode {
- constructor(value) {
- this.value = value;
- this.next = null;
- this.prev = null;
- }
- }
- class DoublyLinkedList {
- constructor(){
- this.head = null;
- this.tail = null;
- }
- addLast(value) {
- const newNode = new LinkedListNode(value)
- if (!this.head) {
- this.tail = newNode;
- this.head = newNode;
- } else {
- this.tail.next = newNode;
- newNode.prev = this.tail;
- this.tail = newNode;
- }
- }
- insertAfter(node, nextNode) {
- if (!node.next) {
- node.next = nextNode;
- nextNode.prev = node;
- nextNode.next = null;
- this.tail = nextNode;
- }
- else {
- nextNode.next = node.next;
- nextNode.prev = node;
- node.next = nextNode;
- nextNode.next.prev = nextNode;
- }
- }
- find(value) {
- let current = this.head;
- while (current !== null) {
- if (current.value === value) {
- return current;
- }
- current = current.next;
- }
- return null;
- }
- values() {
- const values = [];
- let current = this.head;
- while (current !== null) {
- values.push(current.value);
- current = current.next;
- }
- return values;
- }
- remove(node) {
- if (node.prev === null) {
- this.head = node.next;
- this.head.prev = null;
- } else if (node.next === null) {
- this.tail = node.prev;
- this.tail.next = null;
- } else {
- node.prev.next = node.next;
- node.next.prev = node.prev;
- }
- return node
- }
- }
- const linkedList = new DoublyLinkedList();
- for (let i = 1; i<= n; i++) {
- linkedList.addLast(i);
- testMap.set(i, linkedList.find(i));
- }
- for(let i = 0; i< k; i++) {
- const currentNode = testMap.get(arr2[i])
- let final = 0;
- currentNode.value %2 ===0 ? final = currentNode.value / 2 : final = currentNode.value * 2;
- if( final > n ) {
- final = n
- }
- if ( currentNode.value === final) {
- continue;
- }
- const nodeNext = testMap.get(final);
- const removeD = linkedList.remove(currentNode);
- linkedList.insertAfter(nodeNext, removeD);
- }
- print(linkedList.values().join(' '))
Advertisement
Add Comment
Please, Sign In to add comment