Mental Model
Adding an item to the end of a line so that it waits its turn.
Analogy: Imagine a queue at a ticket counter where new people join at the back of the line.
front -> [ ] -> [ ] -> [ ] -> null
βrearfront -> [ ] -> [ ] -> [ ] -> null
βrear1 -> 2 -> 3 -> null newNode(4)
1 -> 2 -> 3 -> [4] -> null
front -> 1 -> 2 -> 3 -> 4 -> null β rear
front -> 1 -> 2 -> 3 -> 4 -> null β rear
class Node { constructor(value) { this.value = value; this.next = null; } } class Queue { constructor() { this.front = null; this.rear = null; } enqueue(value) { const newNode = new Node(value); if (this.rear === null) { this.front = newNode; this.rear = newNode; return; } this.rear.next = newNode; this.rear = newNode; } printQueue() { let curr = this.front; let result = ''; while (curr !== null) { result += curr.value + ' -> '; curr = curr.next; } result += 'null'; console.log(result); } } const queue = new Queue(); queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); queue.enqueue(4); queue.printQueue();
const newNode = new Node(value);if (this.rear === null) {this.front = newNode;
this.rear = newNode;this.rear.next = newNode;this.rear = newNode;if (this.rear === null) {this.rear.next = newNode;
enqueue operation do in a queue data structure?5 to a queue implemented as an array named queue in JavaScript?push() to add elements at the end.queue.push(5); is correct syntax.const queue = []; queue.push(10); queue.push(20); queue.push(30); console.log(queue);
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.unshift(element);
}
}Pass the test and this pattern moves unknown