实战:用两个栈来实现一个队列
整体思路
image
代码编写
package dataStructure.queue;
import org.omg.PortableInterceptor.INACTIVE;
import java.util.Stack;
public class TwoStackOneQueue {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public TwoStackOneQueue(Stack<Integer> stackPush, Stack<Integer> stackPop) {
this.stackPush = stackPush;
this.stackPop = stackPop;
}
/**
* 入队
*/
public void add(int value){
stackPush.push(value);
}
/**
* 出队
*/
public int pop(){
if(stackPush.isEmpty() && stackPop.isEmpty()){
throw new RuntimeException("队列不能为空");
}
if(stackPop.isEmpty()){
while(!stackPush.isEmpty()){
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
public static void main(String[] args) {
TwoStackOneQueue queue = new TwoStackOneQueue(new Stack<>(),new Stack<>());
//入队
queue.add(1);
queue.add(2);
System.out.println(queue.pop());//1
System.out.println(queue.pop());//2
}
}