@wilburn
Простую очередь можно реализовать в node.js с помощью массива или связного списка.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
class Queue { constructor() { this.items = []; } enqueue(element) { this.items.push(element); } dequeue() { if (this.isEmpty()) { return "Queue is empty"; } return this.items.shift(); } isEmpty() { return this.items.length === 0; } size() { return this.items.length; } front() { if (this.isEmpty()) { return "No elements in Queue"; } return this.items[0]; } printQueue() { let str = ""; for (let i = 0; i < this.items.length; i++) { str += this.items[i] + " "; } return str; } } // Пример использования: const queue = new Queue(); console.log(queue.isEmpty()); // true queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); console.log(queue.printQueue()); // 1 2 3 console.log(queue.size()); // 3 console.log(queue.isEmpty()); // false queue.dequeue(); console.log(queue.printQueue()); // 2 3 console.log(queue.front()); // 2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
class Node { constructor(element) { this.element = element; this.next = null; } } class Queue { constructor() { this.head = null; this.tail = null; this.size = 0; } enqueue(element) { const newNode = new Node(element); if (this.isEmpty()) { this.head = newNode; this.tail = newNode; } else { this.tail.next = newNode; this.tail = newNode; } this.size++; } dequeue() { if (this.isEmpty()) { return "Queue is empty"; } const removedNode = this.head; this.head = this.head.next; if (this.head === null) { this.tail = null; } this.size--; return removedNode.element; } isEmpty() { return this.size === 0; } size() { return this.size; } front() { if (this.isEmpty()) { return "No elements in Queue"; } return this.head.element; } printQueue() { let str = ""; let current = this.head; while (current) { str += current.element + " "; current = current.next; } return str; } } // Пример использования: const queue = new Queue(); console.log(queue.isEmpty()); // true queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); console.log(queue.printQueue()); // 1 2 3 console.log(queue.size()); // 3 console.log(queue.isEmpty()); // false queue.dequeue(); console.log(queue.printQueue()); // 2 3 console.log(queue.front()); // 2 |
В обоих случаях мы создаем класс очереди Queue
с методами enqueue
, dequeue
, isEmpty
, size
, front
и printQueue
.