题目
用两个栈实现队列,可以进行 add、poll、peek 操作
代码
/** * @Description:用两个栈实现队列 * @Author: lizhouwei * @CreateDate: 2018/4/5 10:44 * @Modify by: * @ModifyDate: */public class Chapter1_2 { private Stack stack01;//数据栈,压栈的数据 private Stack stack02;//辅助栈,stack01的逆序 public Chapter1_2(){ stack01 = new Stack (); //在new的时候 初始化stack01内存空间 stack02 = new Stack (); //在new的时候 初始化stack02内存空间 } //队尾入 public void add(int value){ //将辅助栈中的元素转移到 01栈中,保证新的元素在以前元素的后面 while(!stack02.isEmpty()){ stack01.push(stack02.pop()); } stack01.push(value); } //队头出 public int poll(){ //如果01栈和02栈都为空,则说明 队列为空了 if(stack01.isEmpty() && stack02.isEmpty() ){ return -1; } //如果02不为空 则说明 是连续的出队列操作,此时所有的元素都在02栈中,直接出02栈即可 if(!stack02.isEmpty() ){ return stack02.pop(); } //02栈为空,将01栈中的元素转移到 02栈中,保证01最底部的元素在02的栈顶 while(!stack01.isEmpty()){ stack02.push(stack01.pop()); } return stack02.pop(); } //查看队头数据 public int peek(){ //如果02栈为空,则说明 队列为空了 if(stack02.isEmpty() ){ return -1; } return stack02.pop(); } public boolean isEmpty(){ //如果01栈和02栈都为空,则说明 队列为空了 return stack01.isEmpty() && stack02.isEmpty(); } //测试 public static void main(String[] args){ Chapter1_2 chapter = new Chapter1_2(); for(int i=10;i<20;i++) { chapter.add(i); } System.out.println(chapter.poll()); for(int i=30;i<40;i++) { chapter.add(i); } System.out.println(chapter.poll()); System.out.println(chapter.poll()); while(!chapter.isEmpty()){ System.out.print(chapter.poll()+" "); } }}