剑指offer系列5---两个栈 模拟队列的操作

【题目】两个栈 模拟队列的入队出队操作

 1 package com.exe1.offer;
 2 
 3 /**
 4  * [题目 ]:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 5  * 队列的出队:应该是队列的列首先出,即栈底元素先出;思路:先把stack1元素一个个弹至上stack2中,再顺序出stack2中数即为队列的出队顺序。
 6  *      入队:先放到栈1中
 7  * @author WGS
 8  *
 9  */
10 import java.util.Stack;
11 
12 public class CreateQueueWithTwoStacks {
13 
14     //1 创建两个栈
15     Stack<Integer> stack1=new Stack<>();
16     Stack<Integer> stack2=new Stack<>();
17     //2 队列的入队操作
18     public void push(int num){
19         stack1.push(num);
20     }
21     //3 队列的出队操作
22     public int pop(){
23         if(stack2.size()<=0){
24             while(stack1.size()>0){
25                 stack2.push(stack1.pop());//先把stack1中元素弹至stack2中,当stack1没有元素的时候,就将stack2元素弹出
26             }
27         }
28         //异常处理
29         if(stack2.size()==0){
30             try{
31                 throw new Exception("empty queue");
32             }catch(Exception e){
33                 e.printStackTrace();
34             }
35         }
36         return stack2.pop();
37     }
38 
39     
40     
41     
42     
43     public static void main(String[] args) {
44         CreateQueueWithTwoStacks cq=new CreateQueueWithTwoStacks();
45         cq.push(1);
46         cq.push(2);
47         cq.push(3);
48         //模拟123顺序进队,下面可看到依然是以先进先出顺序123出
49         System.out.println(cq.pop());
50         System.out.println(cq.pop());
51         System.out.println(cq.pop());
52 
53         //再模拟入队操作,再插入一个数
54         cq.push(4);
55         System.out.println(cq.pop());
56         cq.push(5);
57         System.out.println(cq.pop());
58     }
59 
60 }
原文地址:https://www.cnblogs.com/noaman/p/5379178.html