题目
编写一个类,用两个栈实现队列,支持队列的基本操作(add,poll,peek)。
解法
一个栈作为入队栈,另一个栈作为出队栈。经过两个栈的传递操作可以实现先进先出,满足队列的要求。
import java.util.Stack;
public class twoStackToQueue {
private Stack<Integer> pushStack;
private Stack<Integer> popStack;
public twoStackToQueue() {
this.pushStack = new Stack<Integer>();
this.popStack = new Stack<Integer>();
}
// 入队直接到入队栈就行
public void add(Integer newNum){
this.pushStack.push(newNum);
}
// 出队需要进行判断,当两个栈空时抛出队列空的异常
// 另外分为两种情况:
// 当popStack里面有元素时,popStack出栈即为出队;
// 当popStack里面没有元素时,需要将pushStack的元素全部导入popStack,然后popStack出栈即为出队
public Integer poll(){
if(this.pushStack.isEmpty() && this.popStack.isEmpty()){
throw new RuntimeException("Your queue is empty!");
}else if(popStack.isEmpty()){
while(!this.pushStack.isEmpty()){
this.popStack.push(this.pushStack.pop());
}
}
return this.popStack.pop();
}
//同poll,但是不进行pop操作,使用peek操作
public Integer peek(){
if(this.pushStack.isEmpty() && this.popStack.isEmpty()){
throw new RuntimeException("Your queue is empty!");
}else if(this.popStack.isEmpty()){
while(!this.pushStack.isEmpty()){
this.popStack.push(this.pushStack.pop());
}
}
return this.popStack.peek();
}
}
测试
import twoStackToQueue.twoStackToQueue;
public class twoStackToQueueTest {
public static void main(String[] args) {
twoStackToQueue a = new twoStackToQueue();
a.add(1);
a.add(2);
a.add(3);
System.out.println(a.poll());
a.add(4);
a.add(5);
System.out.println(a.poll());
System.out.println(a.poll());
System.out.println(a.poll());
a.add(6);
System.out.println(a.peek());
}
}