博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用栈实现队列(1)(Java)
阅读量:6977 次
发布时间:2019-06-27

本文共 1907 字,大约阅读时间需要 6 分钟。

1 class MyQueue 2 { 3     private Stack s1; 4     private Stack s2; 5      6     public MyQueue(int size) 7     { 8         this.s1 = new Stack(size); 9         this.s2 = new Stack(size);10     }11     12     public boolean isFull()13     {14         return s1.isFull();15     }16     17     public boolean isEmpty()18     {19         return s1.isEmpty();20     }21     22     //时间复杂度: O(1)23     public void EnQueue(int k) throws Exception24     {25         if(s1.isFull())26             throw new Exception("Overflow.");27         else28             s1.push(k);29     }30     31     //时间复杂度: O(n)32     public int DeQueue() throws Exception33     {34         if(s1.isEmpty())35             throw new Exception("Underflow.");36         else37         {38             for(int i = this.s1.getLength(); i > 1; i--)39                 s2.push(s1.pop());40             int key = s1.pop();41             while(!s2.isEmpty())42                 s1.push(s2.pop());43             return key;44         }45     }46 }47 48 class Stack49 {50     private int top;51     private int[] a;52     53     public Stack(int size)54     {55         this.top = -1;56         this.a = new int[size];57     }58     59     public boolean isFull()60     {61         return this.top == this.a.length - 1;62     }63     64     public boolean isEmpty()65     {66         return this.top == -1;67     }68     69     public void push(int k) throws Exception70     {71         /*if(this.isFull())72             throw new Exception("Overflow.");*/73         //else74             this.a[++top] = k;75     }76     77     public int pop() throws Exception78     {79         /*if(this.isEmpty())80             throw new Exception("Underflow.");*/81         //else82             return this.a[top--];83     }84     85     public int getLength()86     {87         return this.top + 1;88     }89 }

 

转载于:https://www.cnblogs.com/Huayra/p/10690832.html

你可能感兴趣的文章
动态规划算法(java)
查看>>
os模块的几种方法
查看>>
tensorflow API _ 4 (Logging with tensorflow)
查看>>
常用模块------时间模块 , random模块 ,os模块 , sys模块
查看>>
10.02 T3 打表找递推式+十进制快速幂 九校联考凉心模拟DAY1T1
查看>>
leetcode — reverse-linked-list
查看>>
linux 命令 — sort、uniq
查看>>
[python]Python代码安全分析工具(Bandit)
查看>>
向继电器发送socket请求(python+java)
查看>>
20165201 2017-2018-2 《Java程序设计》第一周学习总结
查看>>
7. WebDriver API
查看>>
动软.NET代码生成器实例教程使用总结
查看>>
spring框架学习--依赖注入
查看>>
C语言难点4之动态内存分配
查看>>
[模板] 杜教筛 && bzoj3944-Sum
查看>>
第一次作业
查看>>
SpringBoot2.x的Maven依赖配置
查看>>
17.11.16
查看>>
使用proxyTable 解决webpack+vue-cli+vue-resource中跨域问题
查看>>
页面制作部分之PS切图
查看>>