剑指Offer-7
来源:互联网 发布:网络电视看不到地方台 编辑:程序博客网 时间:2024/06/05 19:41
题目:
用两个栈实现队列
实现
//coding = javapublic class SQueue { private Stack<Integer> stack1 = new Stack(); private Stack<Integer> stack2 = new Stack(); public void add(int data){ stack1.add(data); } public int pop(){ if(stack2.empty()){ while (!stack1.empty()){ stack2.add(stack1.pop()); } } if(stack2.empty()){ throw new RuntimeException("队列为空"); } int result = stack2.pop(); return result; } public static void main(String[] args) throws Exception { SQueue queue = new SQueue(); //入队操作 for (int i = 0; i < 5; i++) { queue.add(i); } //出队操作 System.out.println(queue.pop()); System.out.println(queue.pop()); System.out.println(queue.pop()); }}
用链表实现队列
// coding = javapublic class lQueue { Node head; Node current; public void add(int data){ if(head==null){ head = new Node(data); current=head; } else{ current.next=new Node(data); current=current.next; } } public int pop(){ if(current==null){ throw new RuntimeException("队列为空"); } Node result=head; head=head.next; return result.value; } public static void main(String[] args) throws Exception { lQueue queue = new lQueue(); //入队操作 for (int i = 0; i < 5; i++) { queue.add(i); } //出队操作 System.out.println(queue.pop()); System.out.println(queue.pop()); System.out.println(queue.pop()); }}
用两个队列实现栈
//coding = javapublic class QStack { private Queue<Integer> queue1=new ArrayDeque(); private Queue<Integer> queue2=new ArrayDeque(); public void push(int data){ if(queue1.isEmpty() && queue2.isEmpty()){ queue1.add(data); } else if(queue1.isEmpty() && !queue2.isEmpty()){ queue2.add(data); } else if(!queue1.isEmpty() && queue2.isEmpty()){ queue1.add(data); } } public int pop(){ if(queue1.isEmpty() && queue2.isEmpty()){ throw new RuntimeException("栈为空"); } int result = 0; if(queue1.isEmpty() && !queue2.isEmpty()) { while (!queue2.isEmpty()) { result = queue2.poll(); if (!queue2.isEmpty()) { queue1.add(result); } } } else if (!queue1.isEmpty() && queue2.isEmpty()) { while (!queue1.isEmpty()) { result = queue1.poll(); if (!queue1.isEmpty()) { queue2.add(result); } } } return result; } public static void main(String[] args) throws Exception { QStack stack = new QStack(); stack.push(1); stack.push(2); stack.push(3); System.out.println(stack.pop()); System.out.println(stack.pop()); stack.push(4); }}
阅读全文
1 0
- 剑指Offer-7
- 剑指offer面试题7
- 剑指offer 面试题7
- 剑指offer-面试题7
- 剑指offer[7]跳台阶
- 【面试题】剑指offer 7
- 剑指OFFER
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 剑指Offer
- Keychain 使用
- maven项目docker插件自动部署——jar包
- 网络协议分析工具Wireshark
- 百度鹰眼打包上传失败90087
- 图像分割 DeepLab v2
- 剑指Offer-7
- Java异常处理总结
- js模糊查询
- 使用Kotlin Tools 快速添加Kotlin依赖
- 用人工智能"写诗" 已成为现实【智库2861】
- WCF 运行的时候 报错 提示 “ 同一个协定中不能存在两个名称相同的操作”
- 当Kotlin遇见RxJava多数据源
- java实现发送手机短信
- java根据文件头判断文件格式