package com.my.offer;
import java.util.Stack;
/***
* 用两个栈实现队列add(),poll(),peek()
* 定义两个栈结构stackPush(只做压入栈),stackPop(只做弹出栈)
* 注意两个原则:
* 1>如果要将stackPush中的数据压入stackPop,必须将stackPush中的数据全部压入stackPop
* 2>只有在stackPop为空的时候,才能将stackPush中的数据压入stackPop
* @author asus
*
*/
public class TwoStacksQueue {
//创建压入栈
public Stack<Integer> stackPush;
//创建弹出栈
public Stack<Integer> stackPop;
public TwoStacksQueue() {
stackPush = new Stack<>();
stackPop = new Stack<>();
}
/**
* 将stackPush中的元素压入stackPop
*/
private void pushToPop() {
if(stackPop.isEmpty()) {
//只有当stackPop为空的时候才能进行压入操作
while(!stackPush.isEmpty()) {
//一旦进行压入操作,必须将stackPush中的元素全部压入
stackPop.push(stackPush.pop());
}
}
}
/**
* 模拟入队操作
* @param pushInt
*/
public void add(int pushInt) {
stackPush.push(pushInt);
pushToPop();
}
/**
* 模拟出队操作
* @return
*/
public int poll() {
//判断队列是否为空
if(stackPop.isEmpty() && stackPush.isEmpty()) {
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.pop();
}
/**
* 模拟获取队首元素但不移除
* @return
*/
public int peek() {
if(stackPop.isEmpty() && stackPush.isEmpty()) {
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.peek();
}
}
05-面试题9--用两个栈实现队列
最新推荐文章于 2020-07-12 10:54:16 发布