Skip to content

Commit 495cfa7

Browse files
committed
add solution of problem 232: implement queue using stacks
1 parent 7372d87 commit 495cfa7

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class MyQueue {
2+
private Stack<Integer> stack1 = new Stack<Integer>();
3+
private Stack<Integer> stack2 = new Stack<Integer>();
4+
5+
// Push element x to the back of queue.
6+
public void push(int x) {
7+
stack1.push(x);
8+
}
9+
10+
// Removes the element from in front of queue.
11+
public void pop() {
12+
pushFromStack1ToStack2();
13+
14+
stack2.pop();
15+
}
16+
17+
// Get the front element.
18+
public int peek() {
19+
pushFromStack1ToStack2();
20+
21+
return stack2.peek();
22+
}
23+
24+
// Return whether the queue is empty.
25+
public boolean empty() {
26+
return stack1.empty() && stack2.empty();
27+
}
28+
29+
private void pushFromStack1ToStack2() {
30+
if (stack2.empty()) {
31+
while (!stack1.empty()) {
32+
stack2.push(stack1.pop());
33+
}
34+
}
35+
}
36+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
Implement the following operations of a queue using stacks.
2+
3+
- push(x) -- Push element x to the back of queue.
4+
- pop() -- Removes the element from in front of queue.
5+
- peek() -- Get the front element.
6+
- empty() -- Return whether the queue is empty.
7+
8+
#####Notes:
9+
- You must use *only* standard operations of a stack -- which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid.
10+
- Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
11+
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

0 commit comments

Comments
 (0)