在 Java 中使用两个 Stack 实现 一个 Queue:
package com.test;
import java.util.Stack;
/**
* 用途:
* 开发:zhangmj
* 日期:2018/12/3 15:41
*/
public class Queue<T> {
/**
* 队列: 先进先出
* 栈: 先进后出
*/
private Stack<T> stack_one = new Stack<T>();
private Stack<T> stack_two = new Stack<T>();
// one 1 2 4 5
public void push(T item){
stack_one.push(item);
}
public T pop(){
if(stack_two.empty()){
int size = 5;
if(stack_one.size() < 10){
size = stack_one.size();
}
for (int i = 0; i < size ; i++) {
stack_two.push(stack_one.pop());
}
}
return stack_two.pop();
}
public boolean isNext(){
if(stack_one.empty() && stack_two.empty()){
return false;
}
return true;
}
public static void main(String[] args) {
Queue queue = new Queue();
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(4);
queue.push(5);
queue.push(6);
queue.push(7);
while(queue.isNext()){
System.out.println(queue.pop());
}
queue.push(8);
queue.push(9);
queue.push(10);
queue.push(11);
while(queue.isNext()){
System.out.println(queue.pop());
}
}
}