数据结构--队列实现栈&栈实现队列
来源:互联网 发布:wear软件安装不了 编辑:程序博客网 时间:2024/05/06 08:53
1. 两个栈实现栈
1.这里使用的是ArrayDequeue, 而不是使用Stack,因为Stack 集合是在Java Collection Framework被淘汰的集合。
2. 这里push操作增加的元素放在stack1中;
3. 这里pop操作作用集合为stack2, 如果stack2为空,则将stack1中元素push到stack2中,然后再stack2进行pop()操作。
package com.fqyuan.thought;import java.util.ArrayDeque;public class QueueWithStack { private ArrayDeque<Integer> stack1 = new ArrayDeque<>(); private ArrayDeque<Integer> stack2 = new ArrayDeque<>(); // 1. choose a stack to insert into. public void enqueue(int item) { stack1.push(item); } // 2. if stack2 is empty, move elements of stack1 into stack2, then pop // stack2. public int dequeue() { if (stack2.isEmpty()) while (!stack1.isEmpty()) stack2.push(stack1.pop()); return stack2.pop(); }}
2. 两个队列实现栈
- 由于Queue是接口类型,所以这里在新建Queue对象时需要new具体实现了Queue接口的类, 这里选择了LinkedList。
- 实现时保证,其中一个队列为空,所以在push和pop操作时要满足不同要求。
- push操作向非空的队列中push;pop操作时将非空的队列中的size()-1个元素移到另一个队列,然后弹出最后一个元素即可。
package com.fqyuan.thought;import java.util.LinkedList;import java.util.Queue;import java.util.Random;public class StackWithQueue { private Queue<Integer> queue1 = new LinkedList<>(); private Queue<Integer> queue2 = new LinkedList<>(); // 1. 往非空的队列中放元素 public void push(int item) { if (queue1.isEmpty()) queue2.offer(item); else queue1.offer(item); } // 2. 始终有一个队列为空,现将一个队列元素(n-1)个移动到另一个队列,然后将最后一个元素弹出。 public int pop() { if (isEmpty()) return -1; if (queue1.isEmpty()) { while (queue2.size() > 1) queue1.offer(queue2.poll()); return queue2.poll(); } else { while (queue1.size() > 1) queue2.offer(queue1.poll()); return queue1.poll(); } } public int top() { if (queue1.isEmpty()) { while (queue2.size() > 1) queue1.offer(queue2.poll()); int item = queue2.poll(); queue1.offer(item); return item; } else { while (queue1.size() > 1) queue2.offer(queue1.poll()); int item = queue1.poll(); queue2.offer(item); return item; } } public boolean isEmpty() { return queue1.isEmpty() && queue2.isEmpty(); }}
阅读全文
1 0
- 数据结构--队列实现栈&栈实现队列
- java数据结构,实现栈/队列
- java实现栈,队列数据结构
- java实现 数据结构:链表、 栈、 队列、优先级队列、哈希表
- 常用数据结构STL实现(优先队列、队列、栈)
- 【数据结构】队列以及两个队列实现一个栈
- 用两个栈实现队列[数据结构]
- 用两个栈实现队列[数据结构]
- 【数据结构】两个栈实现一个队列
- 数据结构队列及栈的实现
- 数据结构(24)队列--两个栈实现
- 数据结构-使用两个栈实现一个队列
- 【数据结构】用两个队列实现一个栈
- 【数据结构】 两个栈实现一个队列【面试】
- 【数据结构】两个队列实现一个栈
- 数据结构:模板实现栈和队列
- 数据结构:用队列实现栈 C++
- 【数据结构】用两个栈实现队列
- 微软消息队列-MSMQ
- Java-数字黑洞 (20)
- 【复习笔记】计算机网络求职考点整理
- 浮点数在计算机中的存储方式
- ConcurrentHashMap源码分析
- 数据结构--队列实现栈&栈实现队列
- Android 反编译 -smali语法
- 洛谷1040 加分二叉树
- SecureRandom漏洞解析
- 哈老师抄来的比赛之心灵治愈
- python中if __name__=="__main__":
- instanceof 运算符
- Python3之基于tcp模拟ssh远程执行命令
- web——CSS中position属性( absolute 、 relative 、static 、 fixed )详解