package StackAndQueueSummary;
import java.util.Stack;
/**
* 3.用两个栈实现队列
* 实现对列,就是要实现它的3个方法:enqueue(入队),dequeue(出对),peek(队头)
* 基本思路:
* (1)stack1 存的是每次进来的元素,所以enqueue就是把进来的元素存入push到stack1中。
* (2)而对于dequeue,一开始stack2是空的,所以我们把stack1 中的元素全部pop到stack2中,
* 这样stack2的栈顶就是队头。只要stack2 不为空,那么每次出队,就相当于执行stack2 的pop操作。
* (3)接下来,每入队一个元素,仍然push到stack1 中。没出对一个元素,只要stack2 不为空,就从stack2 中pop一个元素;
* 如果stack2 为空,就重复上面的操作--把stack1中的元素pop到stack2中。
* (4)peek操作,类似于dequeue,只是不需要出队,所以我们调用stack2中的peek操作。如果stack2为空,就把stack1中的元素全部pop到
* stack2中。
* (5)注意边界的处理,如果stack2和stack1都为空,才等于队列为空,此时不能进行peek操作和dequeue操作。
*
*
*/
public class NewQueue<E> {
private Stack<E> stack1 ;//用来执行入队操作
private Stack<E> stack2;//用来执行出队操作
public NewQueue(){
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void enqueue(E item){
stack1.push(item);
}
public E dequeue() throws Exception{
//如果stack1 和stack2都为空,说明队列为空,抛出异常
if(stack1.isEmpty() && stack2.isEmpty()){
throw new Exception("The queue is empty");
}
//若队列不为空,但是stack2 为空,那么就将stack1中所有的元素pop到stack2中
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
//出队操作相当于stack2执行pop
return stack2.pop();
}
public E peek() throws Exception{
//如果stack1 和stack2都为空,说明队列为空,抛出异常
if(stack1.isEmpty() && stack2.isEmpty()){
throw new Exception("The queue is empty");
}
//若队列不为空,但是stack2 为空,那么就将stack1中所有的元素pop到stack2中
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
//获取队头元素相当于stack2执行peek
return stack2.peek();
}
public static void main(String[] args) throws Exception {
NewQueue<String> newQueue = new NewQueue<>();
newQueue.enqueue("a");
newQueue.enqueue("b");
newQueue.enqueue("c");
System.out.println(newQueue.peek());//a
System.out.println(newQueue.dequeue());//a
System.out.println(newQueue.dequeue());//b
System.out.println(newQueue.dequeue());//c
newQueue.enqueue("1");
newQueue.enqueue("2");
newQueue.enqueue("3");
System.out.println(newQueue.dequeue());//1
}
}