【剑指offer】 用两个栈实现队列 -Java
来源:互联网 发布:鬼吹灯 盗墓笔记 知乎 编辑:程序博客网 时间:2024/06/05 19:44
如有不足,请批评指正
1构建队
import java.util.Stack;public class MyQueue {static Stack<Character> stack1=new Stack<>();static Stack<Character> stack2=new Stack<>();public void enQueue(char ch){stack1.push(ch);}public MyQueue(Character[] array){for(int i=0;i<array.length;i++)enQueue(array[i]);}public MyQueue() {// TODO Auto-generated constructor stub}public void deQueue( ){if(stack1.isEmpty()) return;while(stack1.isEmpty()==false){char ch=stack1.pop();stack2.push(ch);}stack2.pop();while(stack2.isEmpty()==false){ char ch=stack2.pop();stack1.push(ch);}}public void print(){System.out.println("the items in the queue are:");if(stack1.isEmpty()) return;while(stack1.isEmpty()==false){char ch=stack1.pop();stack2.push(ch);}//stack2.pop();while(stack2.isEmpty()==false){ char ch=stack2.pop();System.out.print(ch+" ");stack1.push(ch);}System.out.println();}}
2 测试结果:
public class TestMyQueue {public static void main(String[] args){Character[] array={'A','B','C','D'};MyQueue queue=new MyQueue(array);queue.print();queue.deQueue();queue.print();queue.enQueue('E');queue.print();queue.deQueue();queue.print();queue.deQueue();queue.print();queue.deQueue();queue.print();queue.deQueue();queue.print();}}实验结果:
the items in the queue are:A B C D the items in the queue are:B C D the items in the queue are:B C D E the items in the queue are:C D E the items in the queue are:D E the items in the queue are:E the items in the queue are:
0 0
- 《剑指offer》用两个队列实现栈 Java版实现
- 【剑指offer-Java版】07用两个栈实现队列
- 剑指offer-Java-用两个栈实现队列
- 【剑指offer】 用两个栈实现队列 -Java
- 剑指offer-----用两个栈实现队列(java版)
- 《剑指offer》牛客网java题解-用两个栈实现队列
- 剑指offer:用两个栈实现队列、用两个队列实现一个栈(java)
- [剑指offer]用两个栈实现队列
- 【剑指offer】用两个栈实现队列
- 剑指offer--用两个栈实现队列
- 剑指Offer-用两个栈实现队列
- 剑指offer:用两个栈实现队列
- 《剑指offer》用两个栈实现队列
- 用两个栈实现队列(剑指offer)
- 剑指 offer:用两个栈实现队列
- 【剑指Offer】用两个栈实现队列
- 剑指offer-用两个栈实现队列
- 《剑指offer》-用两个栈实现队列
- Transform.TransformDirection
- 正则表达式(RegExp)的方法和字符串的模式匹配方法
- Linux的文件类型和权限
- Java在cmd下编译eclipse代码
- contentProvider
- 【剑指offer】 用两个栈实现队列 -Java
- 【LeetCode-101】 Symmetric Tree(C++)
- Apache Phoenix的Join操作和优化
- android 代码混淆与反编译
- Enum源码分析
- CI框架SESSION使用
- 【MySQL 14】触发器after和before
- Unity Shader-后处理:简单的颜色调整(亮度,饱和度,对比度)
- velocity判断空和null