zoukankan      html  css  js  c++  java
  • 用两个Stack来实现一个Queue

     1 import java.util.Stack;
     2 
     3 /**
     4  * 问题:用两个Stack来实现一个Queue;
     5  * 方法:栈的特点是先进后出;而队列的特点是先进先出;
     6  *     用两个栈正好能把顺序调过来;
     7  *     一个栈,作为压入栈,在压入数据时,只往这个栈里压入,记作:stackPush;
     8  *     一个栈 ,作为弹出栈,在弹出数据时,只从这个栈里弹出,记作:stackPop;
     9  *
    10  */
    11 public class TwoStackQueue {
    12     private Stack<Integer> stackPush;
    13     private Stack<Integer> stackPop;
    14     
    15     public TwoStackQueue(){
    16         this.stackPush = new Stack<Integer>();
    17         this.stackPop = new Stack<Integer>();
    18     }
    19     
    20     //向队列中添加元素;
    21     public void add(int pushInt) {
    22         stackPush.push(pushInt);
    23     }
    24     
    25     //从队列中删除元素;
    26     public int poll() {
    27         if(stackPop.empty() && stackPush.empty()) {
    28             throw new RuntimeException("Queue is empty!");
    29         } else if(stackPop.empty()) {
    30             while(!stackPush.empty()) {
    31                 stackPop.push(stackPush.pop());
    32             }
    33         }
    34         return stackPop.pop();
    35     }
    36     
    37     //得到位于队头位置元素的值;
    38     public int peek() {
    39         if(stackPop.empty() && stackPush.empty()) {
    40             throw new RuntimeException("Queue is empty!");
    41         } else if(stackPop.empty()) {
    42             while(!stackPush.empty()) {
    43                 stackPop.push(stackPush.pop());
    44             }
    45         }
    46         return stackPop.peek();
    47         
    48     }
    49     
    50     //测试程序
    51     public static void main(String[] args) {
    52         TwoStackQueue tsq = new TwoStackQueue();
    53         int[] a = {1, 2, 3, 4, 5, 6, 7};
    54         for(int i: a){
    55             tsq.add(i);
    56         }
    57         
    58         for(int j=0; j<a.length; j++) {
    59             int num = tsq.peek();
    60             tsq.poll();
    61             System.out.println(num);
    62         }
    63     }
    64     
    65 }

    如果我引用您的博文记录,没有指出,请求您的原谅。可以私信告诉我,我一定改正! 注:我写博文的目的主要是记录得失,若有什么误人子弟的地方,请多多见谅指正;
  • 相关阅读:
    mysql5.7 linux安装参考
    谈谈微服务中的 API 网关(API Gateway)
    十大Intellij IDEA快捷键
    SqoopFlume、Flume、HDFS之间比较
    PostgreSQL-存储过程(一)基础篇
    spark调优篇-oom 优化(汇总)
    spark调优篇-数据倾斜(汇总)
    spark调优篇-Spark ON Yarn 内存管理(汇总)
    spark异常篇-OutOfMemory:GC overhead limit exceeded
    spark异常篇-Removing executor 5 with no recent heartbeats: 120504 ms exceeds timeout 120000 ms 可能的解决方案
  • 原文地址:https://www.cnblogs.com/zhaojinxin/p/5410296.html
Copyright © 2011-2022 走看看