题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

题解一:
 //stack2有元素就pop,没有元素就将stack1中所有元素倒进来再pop
     public static void push(int node) {
          stack1.push(node);
     }
     public static int pop() {
         if(stack1.isEmpty()&&stack2.isEmpty()){
             throw new RuntimeException("Queue is empty!");
         }
         if(stack2.isEmpty()){
             while (!stack1.isEmpty()){
                 stack2.push(stack1.pop());
             }
         }
         return stack2.pop();
     }
题解二:
 //每次psuh是时先将stack2清空放入stck1(保证选入的一定在栈底),stack2始终是用来删除的
     //在pop前,先将stack1中中的数据清空放入stack2(保存后入的在栈底),stack1始终用于push
     public static void push01(int node) {
         while(!stack2.isEmpty()){
             stack1.push(stack2.pop());
         }
         stack1.push(node);
     }

     public static int pop01() {
         while (!stack1.isEmpty()){
             stack2.push(stack1.pop());
         }
         return stack2.pop();
     }

测试:

 public static void main(String[] args) {
         String[] order={"PUSH_1","PUSH_2","PUSH_3","POP","POP","PUSH_4","POP","PUSH_5","POP","POP"};
         for(int i=0;i<order.length;i++){
             String s = order[i].toString();
             String[] strings = s.split("_");
             if(strings[0].equals("PUSH")){
                 int parseInt = Integer.parseInt(strings[1]);
                 push(parseInt);
             }
             if(strings[0].equals("POP")){
                 int pop = pop();
                 System.out.print(pop+" ");
             }
         }
     }
 输出:1 2 3 4 5

最新文章

  1. 神秘代理-Proxy
  2. Bootstrap&lt;基础一&gt; CSS 概览
  3. 解决虚拟机 MAC10.9 不能设置1366*768分辨率问题
  4. OpenStack主机列表接口
  5. JSBinding + SharpKit / 安装SharpKit以及添加SharpKit工程
  6. json封装与解析
  7. [cocoapods]cocoapods问题解决
  8. hadoop 任务执行优化
  9. 在ubuntu上面配置nginx实现反向代理
  10. rnqoj-99-配置魔药-dp
  11. jquery 上下滑动效果
  12. Oracle使用rowid删除重复记录
  13. Linux下栈溢出导致的core dump
  14. Java面向对象 线程技术 -- 下篇
  15. 【ASP.NET MVC 学习笔记】- 09 Area的使用
  16. 【ASP.NET Core分布式项目实战】(三)整理IdentityServer4 MVC授权、Consent功能实现
  17. Python_自定义递归的最大深度
  18. 4. Scala程序流程控制
  19. 关于2-sat的建图方法及解决方案
  20. java集合: LinkedList源码浅析

热门文章

  1. 快速理解 VUEX 原理
  2. webpack入门系列2
  3. Python趣味入门01:你真的了解Python么?
  4. HDU_3853_概率dp
  5. 拖延症?贪玩?来试试&quot;百万金币时间管理法&quot;
  6. Mysql事务结合spring管理
  7. 【机器学习】算法原理详细推导与实现(六):k-means算法
  8. day14 jQuery
  9. 编译安装php依赖软件libiconv-1.14报错及其解决办法
  10. lua 打印一个table的实现