Realize queue with stack based on java
topic description
Please use only two stacks to implement a first-in-first-out queue. The queue should support all operations supported by general queues (push, pop, peek, empty):
Implement the MyQueue class:
void push(int x) 将元素 x 推到队列的末尾 int pop() 从队列的开头移除并返回元素 int peek() 返回队列开头的元素 boolean empty() 如果队列为空,返回 true ;否则,返回 false
Note:
You can only use standard stack operations—that is, only push to top, peek/pop from top, size, and is empty operations are legal.
Your language may not support stacks. You can use list or deque (double-ended queue) to simulate a stack, as long as it is a standard stack operation.
example
answer
import javautil.Stack;
class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
if(empty()){
return -1;
}
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
int ret = stack1.pop();
stack2.push(ret);
}
}
return stack2.pop();
}
public int peek() {
if(empty()){
return -1;
}
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
int ret = stack1.pop();
stack2.push(ret);
}
}
return stack2.peek();
}
public boolean empty() {
if(stack1.isEmpty() && stack2.isEmpty()){
return true;
}
return false;
}
}