|
| 1 | +// Stack using queues |
| 2 | +class StackUsingQueues { |
| 3 | + constructor() { |
| 4 | + this.primaryQueue = []; |
| 5 | + this.tempQueue = []; |
| 6 | + } |
| 7 | + |
| 8 | + // Push an element onto the stack. |
| 9 | + push(x) { |
| 10 | + // Add the element to the primary queue. |
| 11 | + this.primaryQueue.push(x); |
| 12 | + } |
| 13 | + |
| 14 | + // Remove and return the top element of the stack. |
| 15 | + pop() { |
| 16 | + if (this.isEmpty()) { |
| 17 | + throw new Error("Stack is empty"); |
| 18 | + } |
| 19 | + |
| 20 | + // Move elements from the primary queue to the temporary queue except the last one. |
| 21 | + while (this.primaryQueue.length > 1) { |
| 22 | + this.tempQueue.push(this.primaryQueue.shift()); |
| 23 | + } |
| 24 | + |
| 25 | + // Get the last element from the primary queue (top of the stack). |
| 26 | + const topElement = this.primaryQueue.shift(); |
| 27 | + |
| 28 | + // Swap the primary and temporary queues. |
| 29 | + [this.primaryQueue, this.tempQueue] = [this.tempQueue, this.primaryQueue]; |
| 30 | + |
| 31 | + return topElement; |
| 32 | + } |
| 33 | + |
| 34 | + // Return the top element of the stack without removing it. |
| 35 | + top() { |
| 36 | + if (this.isEmpty()) { |
| 37 | + throw new Error("Stack is empty"); |
| 38 | + } |
| 39 | + |
| 40 | + const topElement = this.pop(); |
| 41 | + |
| 42 | + // Add the top element back to the stack. |
| 43 | + this.push(topElement); |
| 44 | + |
| 45 | + return topElement; |
| 46 | + } |
| 47 | + |
| 48 | + // Check if the stack is empty. |
| 49 | + isEmpty() { |
| 50 | + return this.primaryQueue.length === 0; |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +const stack = new StackUsingQueues(); |
| 55 | + |
| 56 | +// Push elements onto the stack. |
| 57 | +stack.push(1); |
| 58 | +stack.push(2); |
| 59 | +stack.push(3); |
| 60 | + |
| 61 | +// Pop elements from the stack. |
| 62 | +console.log(stack.pop()); // Output: 3 |
| 63 | +console.log(stack.pop()); // Output: 2 |
| 64 | + |
| 65 | +// Push more elements. |
| 66 | +stack.push(4); |
| 67 | +stack.push(5); |
| 68 | + |
| 69 | +// Peek at the top element. |
| 70 | +console.log(stack.top()); // Output: 5 |
| 71 | + |
| 72 | +// Check if the stack is empty. |
| 73 | +console.log(stack.isEmpty()); // Output: false |
0 commit comments