Skip to content

Commit fab1558

Browse files
committed
Implement Stack using Queues
1 parent 2313e0f commit fab1558

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Implement Stack using Queues.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*Implement the following operations of a stack using queues.
2+
3+
push(x) -- Push element x onto stack.
4+
pop() -- Removes the element on top of the stack.
5+
top() -- Get the top element.
6+
empty() -- Return whether the stack is empty.
7+
Notes:
8+
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.
9+
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.
10+
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).*/
11+
12+
/**
13+
* Initialize your data structure here.
14+
*/
15+
var MyStack = function() {
16+
this.stack = []
17+
};
18+
19+
/**
20+
* Push element x onto stack.
21+
* @param {number} x
22+
* @return {void}
23+
*/
24+
MyStack.prototype.push = function(x) {
25+
this.stack.push(x)
26+
};
27+
28+
/**
29+
* Removes the element on top of the stack and returns that element.
30+
* @return {number}
31+
*/
32+
MyStack.prototype.pop = function() {
33+
return this.stack.pop()
34+
};
35+
36+
/**
37+
* Get the top element.
38+
* @return {number}
39+
*/
40+
MyStack.prototype.top = function() {
41+
return this.stack[this.stack.length-1]
42+
};
43+
44+
/**
45+
* Returns whether the stack is empty.
46+
* @return {boolean}
47+
*/
48+
MyStack.prototype.empty = function() {
49+
return this.stack[0] == null
50+
};
51+
52+
/**
53+
* Your MyStack object will be instantiated and called as such:
54+
* var obj = Object.create(MyStack).createNew()
55+
* obj.push(x)
56+
* var param_2 = obj.pop()
57+
* var param_3 = obj.top()
58+
* var param_4 = obj.empty()
59+
*/

0 commit comments

Comments
 (0)