数组模拟队列
来源:互联网 发布:什么叫数据标签 编辑:程序博客网 时间:2024/06/12 00:49
import java.lang.ref.SoftReference;/** * 使用数组模拟Java的队列 * 1.在队列尾添加元素void add(E e) * 2.删除队列头的元素E remove() * 3.访问队列头的元素E peek() * 4.获得队列大小int size() * 5.判断队列是否为空boolean isEmpty() * 6.清空队列void clear() * **/class QueueDemo<E>{private int LENGTH;private int SIZE;private int ADD;private int REMOVE;Object[] o;public QueueDemo(){this.SIZE=0;this.REMOVE=0;this.ADD=0;this.LENGTH=1;this.o=new Object[1];}public void add(E e){this.o[this.SIZE++]=e;this.ADD++;if(this.SIZE==this.LENGTH)this.copy();}public E remove(){if(this.ADD-this.REMOVE==0)throw new ArrayIndexOutOfBoundsException();E temp=(E)this.o[this.REMOVE++];this.o[this.REMOVE-1]=null;return temp;}public E peek(){if(this.ADD-this.REMOVE==0)throw new ArrayIndexOutOfBoundsException();return (E)this.o[this.SIZE-1];}public int size(){return this.ADD-this.REMOVE;}public boolean isEmpty(){if(this.ADD-this.REMOVE==0)return true;return false;}public void clear(){this.SIZE=0;this.REMOVE=0;this.ADD=0;this.LENGTH=1;this.o=new Object[1];}private void copy(){Object[] temp=new Object[this.LENGTH*2];this.LENGTH*=2;int count=0;SoftReference<Object[]> sr=new SoftReference<Object[]>(temp);for(int i=0;i<this.SIZE;i++)if(this.o[i]!=null)temp[count++]=this.o[i];this.o=temp;temp=null;this.SIZE=count;this.ADD=count;this.REMOVE=0;}public String toString(){if(this.ADD-this.REMOVE==0)return "[]";StringBuilder sb=new StringBuilder();SoftReference<StringBuilder> sr=new SoftReference<StringBuilder>(sb);sb.append("["); for(int i=this.REMOVE;i<this.SIZE-1;i++)sb.append(this.o[i]+","); sb.append(this.o[this.SIZE-1]+"]"); String str=sb.toString(); sb=null; return str;}}//测试用码public class QueueTest {public static void main(String[] args){QueueDemo<String> qd=new QueueDemo<String>();qd.add("aaaa");qd.add("llll");System.out.println(qd);System.out.println(qd.remove());System.out.println(qd);System.out.println(qd.remove());System.out.println(qd);System.out.println(qd.isEmpty());qd.add("pppp");qd.add("pppp");System.out.println(qd.size());System.out.println(qd.isEmpty());System.out.println(qd.peek());System.out.println(qd);}}
0 0
- 数组模拟循环队列
- 数组模拟队列
- 队列(数组模拟)
- 队列(数组模拟)
- 数组模拟队列
- Java 数组模拟队列
- 数据结构03.1 队列模拟(数组)
- 用数组模拟 优先级队列
- 数组模拟队列和栈
- 数组模拟队列 广搜
- JAVA使用数组简单模拟队列
- uva 12100 Printer Queue 优先级队列模拟题 数组模拟队列
- hdu 1237 简单计算器(数组模拟栈,队列)
- 队列——排队买饭(数组模拟法)
- bfs+路径记录(数组模拟队列实现)
- 数组模拟链表之P1160 队列安排
- hdu_1285_拓扑排序入门_数组模拟_队列优化
- 邻接表用数组模拟+dij+优先队列,dfs剪枝+邻接表用数组模拟,链表+dij+优先队列
- 处女男学Android(十一)---Gallery、ViewPager和ViewPager+Fragment实现的Tab导航
- Java输出字符串大小写字母个数【Java学习笔记】
- HDU 5146 Sequence 判断序列不是回文 且奇数与偶数位的和不同
- hdu 3065 病毒侵袭持续中(AC自动机)
- 简介JAVA IO
- 数组模拟队列
- 经典笔试题目
- HDU1285 确定比赛名次【拓扑排序】【优先队列】
- 非齐次方程组代码(C++)
- 【AngularJS系列2】scope - reeoo
- ACdreM-1061 郭式树 没文化真可怕
- HDU 1014 Uniform Generator 循环判断
- 文件类型
- hdu5144 三分