Acwing_20 用两个栈实现队列
用栈实现一个队列,支持如下四种操作:
- push(x) – 将元素x插到队尾;
- pop() – 将队首的元素弹出,并返回该元素;
- peek() – 返回队首元素;
- empty() – 返回队列是否为空;
**栈的特点是先进后出,队列的特点是先进先出**
注意:
1、stackPush栈往stackPop栈中压入数据时,要一次性全部压入
2、如果stackPop栈中不为空,则不能向stackPop栈中压入数据
代码如下:
public class MyQueue {
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.push(3);
int temp1 = queue.pop();
int temp2 = queue.peek();
boolean temp3 = queue.empty();
System.out.println(temp1);
System.out.println(temp2);
System.out.println(temp3);
}
public Stack<Integer> stackPush; //压入栈
public Stack<Integer> stackPop; //弹出栈
//栈的初始化操作
public MyQueue(){
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
//入栈
public void push(int value){
stackPush.push(value);
}
//出栈
public int pop(){
if (!stackPush.empty()){
while (!stackPush.empty()){
stackPop.push(stackPush.pop());
}
return stackPop.pop();
}else {
throw new RuntimeException("Queue is empty!");
}
}
//获取队首元素
public int peek(){
if (stackPop.empty()){
throw new RuntimeException("Queue is empty!");
}else {
return stackPop.peek();
}
}
//判断队列是否为空
public boolean empty(){
if (stackPop.empty()){
return true;
}else {
return false;
}
}
}