Skip to content

Commit 6f1d1cc

Browse files
authored
Merge pull request #1759 from akgmage/dev
Dev
2 parents 91be218 + df8fa9c commit 6f1d1cc

File tree

4 files changed

+76
-3
lines changed

4 files changed

+76
-3
lines changed

Stacks/stack_using_queue.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// stack using queue
1+
// stack using queues
22
#include <iostream>
33
#include <queue>
44

Stacks/stack_using_queue.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// stack using queue
1+
// stack using queues
22
package main
33

44
import (

Stacks/stack_using_queue.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// stack using queue
1+
// stack using queues
22
import java.util.LinkedList;
33
import java.util.Queue;
44

Stacks/stack_using_queue.js

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
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

Comments
 (0)