用两个栈实现一个队列
栈为后来居上,先进后出的数据结构,而队列为先进先出,可以用两个栈实现队列的特性:
- 申请两个栈:
stackPush
和stackPop
。
stackPush
用来“压数”,就和普通的栈一样的作用
stackPop
实现stackPush
内元素的倒序,用以实现先进先出- 队列的
add()
方法,即stackPush.push()
- 队列的
poll()
和peek()
则要依赖stackPop
,具体如下:
poll()
时,如果stackPop
为空,则从stackPush
内逐一出栈然后压入stackPop
中【及实现了stackPush
内元素的倒序
- 如
stackPop
不为空,则直接从stackPop
出栈
peek()
的实现同理
代码实现如下:
package com.lilydedbb;
import java.util.Stack;
/**
* Created by dbb on 2016/12/23.
*/
public class TwoStackQueue {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public TwoStackQueue(){
this.stackPush = new Stack<Integer>();
this.stackPop = new Stack<Integer>();
}
public void add(int newNumber){
this.stackPush.push(newNumber);
}
public int poll(){
if(this.stackPop.isEmpty() && this.stackPush.isEmpty()){
throw new RuntimeException("The Queue is empty");
}else if(this.stackPop.isEmpty()){
while (!this.stackPush.isEmpty())
this.stackPop.push(this.stackPush.pop());
}
return this.stackPop.pop();
}
public int peek(){
if(this.stackPop.isEmpty() && this.stackPush.isEmpty()){
throw new RuntimeException("The Queue is empty");
}else if(this.stackPop.isEmpty()){
while (!this.stackPush.isEmpty())
this.stackPop.push(this.stackPush.pop());
}
return this.stackPop.peek();
}
}