Skip to content

Commit 27a133e

Browse files
Added implement stack using queues
1 parent 78c9305 commit 27a133e

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
/*
2+
Implement Stack using Queues
3+
URL: https://leetcode.com/problems/implement-stack-using-queues/description/
4+
5+
Implement the following operations of a stack using queues.
6+
7+
push(x) -- Push element x onto stack.
8+
pop() -- Removes the element on top of the stack.
9+
top() -- Get the top element.
10+
empty() -- Return whether the stack is empty.
11+
Example:
12+
13+
MyStack stack = new MyStack();
14+
15+
stack.push(1);
16+
stack.push(2);
17+
stack.top(); // returns 2
18+
stack.pop(); // returns 2
19+
stack.empty(); // returns false
20+
Notes:
21+
22+
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
23+
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
24+
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
25+
*/
26+
27+
28+
29+
class MyStack {
30+
constructor() {
31+
this.q1 = [];
32+
this.q2 = [];
33+
};
34+
35+
push(elem) {
36+
if(this.q1.length > 0) {
37+
this.q1.push(elem);
38+
} else {
39+
this.q2.push(elem);
40+
}
41+
};
42+
43+
pop() {
44+
if(this.q1.length === 0 && this.q2.length === 0)
45+
return null;
46+
47+
if(this.q1.length > 0) {
48+
while(this.q1.length > 1) {
49+
var elem = this.q1.shift();
50+
this.q2.push(elem);
51+
}
52+
return this.q1.shift();
53+
} else {
54+
while(this.q2.length > 1) {
55+
var elem = this.q2.shift();
56+
this.q1.push(elem);
57+
}
58+
return this.q2.shift();
59+
}
60+
};
61+
62+
top() {
63+
if(this.q1.length === 0 && this.q2.length === 0)
64+
return null;
65+
66+
if(this.q1.length > 0) {
67+
var elem = this.pop();
68+
this.q2.push(elem);
69+
return elem;
70+
} else {
71+
var elem = this.pop();
72+
this.q1.push(elem);
73+
return elem;
74+
}
75+
};
76+
77+
empty() {
78+
return this.q1.length == 0 && this.q2.length === 0;
79+
};
80+
}
81+
82+
var main = function() {
83+
84+
var myStack = new MyStack();
85+
myStack.push(4);
86+
myStack.push(3);
87+
myStack.push(2);
88+
myStack.push(1);
89+
console.log(myStack.pop());
90+
console.log(myStack.top());
91+
console.log(myStack.push(1));
92+
console.log(myStack.top());
93+
console.log(myStack.pop());
94+
console.log(myStack.pop());
95+
console.log(myStack.pop());
96+
}
97+
98+
module.exports.main = main;

0 commit comments

Comments
 (0)