栈特性:先进后出
队列特性:先进先出
思路:将栈中元素颠倒一次即可得到队列顺序。
package cn.ruyipay.test;
import java.util.Stack;
/**
* @program:tpb
* @description:双栈实现队列入队和出队
* @author:heshuangxi
* @create:2020-08-28 08:51
**/
public class DoubleStackImplementsQueue {
static Stack<Integer> stackOne = new Stack<>();
static Stack<Integer> stackTwo = new Stack<>();
public static void main(String[] args) {
System.out.println(offer(1));
System.out.println(poll());
System.out.println(offer(2));
System.out.println(offer(3));
System.out.println(poll());
System.out.println(poll());
System.out.println(poll());
}
public static boolean offer(int element) {
return element == stackOne.push(element);
}
public static int poll() {
if (stackTwo.empty()) {
if (stackOne.size() == 1) {
return stackOne.pop();
}
if(stackOne.empty()){
throw new RuntimeException("Queue is Empty!");
}
while (!stackOne.empty()) {
stackTwo.push(stackOne.pop());
}
}
return stackTwo.pop();
}
}
思考:1.为什么poll()方法直接判断stackTwo是否empty()?
stackTwo不为empty()直接进行stackTwo.pop()乐观思想,
连续多次offer后第一次poll稍慢点,之后节省了判断stackOne.emty()时间。
2.为什么poll()方法添加stackOne.size() == 1判断?
避免了stackOne只有一个元素时颠倒到stackTwo栈。
3.为什么使用 empty()没有使用 isEmpty()?
isEmpty()是父类的Vector的synchronized方法,
empty()是stack方法,底层使用了Vector中size()的synchronized方法。
本人理解使用哪个都可以。