Skip to content

Commit c8ef817

Browse files
committed
implement queue using stack
1 parent af0b0bb commit c8ef817

2 files changed

Lines changed: 59 additions & 1 deletion

File tree

‎DataStructures/Queue/Algorithms_toDo.md‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
+ Range Sum Query - Immutable (LeetCode #303)
88
+ Implement Stack using Queue (LeetCode #225)
9-
+ Implement Queue using Stacks (LeetCode #232)
109
+ Lemonade Change (LeetCode #860)
1110
+ Sum of Even Numbers After Queries (LeetCode #985)
1211

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Initialize your data structure here.
3+
*/
4+
var MyQueue = function() {
5+
this.front = [];
6+
this.back = [];
7+
};
8+
9+
/**
10+
* Push element x to the back of queue.
11+
* @param {number} x
12+
* @return {void}
13+
*/
14+
MyQueue.prototype.push = function(x) {
15+
this.front.push(x);
16+
};
17+
18+
/**
19+
* Removes the element from in front of queue and returns that element.
20+
* @return {number}
21+
*/
22+
MyQueue.prototype.pop = function() {
23+
if (!this.back.length) {
24+
while (this.front.length) {
25+
this.back.push(this.front.pop());
26+
}
27+
}
28+
return this.back.pop();
29+
};
30+
31+
/**
32+
* Get the front element.
33+
* @return {number}
34+
*/
35+
MyQueue.prototype.peek = function() {
36+
if (!this.back.length) {
37+
while (this.front.length) {
38+
this.back.push(this.front.pop());
39+
}
40+
}
41+
return this.back[this.back.length - 1];
42+
};
43+
44+
/**
45+
* Returns whether the queue is empty.
46+
* @return {boolean}
47+
*/
48+
MyQueue.prototype.empty = function() {
49+
return !this.front.length && !this.back.length;
50+
};
51+
52+
/**
53+
* Your MyQueue object will be instantiated and called as such:
54+
* var obj = new MyQueue()
55+
* obj.push(x)
56+
* var param_2 = obj.pop()
57+
* var param_3 = obj.peek()
58+
* var param_4 = obj.empty()
59+
*/

0 commit comments

Comments
 (0)