Skip to content

Commit b1ae2f9

Browse files
committed
1021
1 parent a4802d3 commit b1ae2f9

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

java/QueueUsingStacks.java

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

0 commit comments

Comments
 (0)