词条 | 环形队列 |
释义 | 程序是用codeblock写的,中间碰到了一个又一个的问题,都最终解决了。这个结构可以作为所有结构体的实现的一个模式。写写这些程序可以不断让自己更加深入认识指针,更加熟悉指针的各种使用。 实现方式,利用一个入队游标和一个出队游标来定制一个数组而构造一个环形队列: (JAVA版实现:) /** * 环形队列 * @author Zhongzhou Han */ public class CircularQueue { //队列原型数组 private Object[] queue; //入队与出队游标 private int inIndex,outIndex = 0; boolean empty,full; public CircularQueue(int size) { queue = new Object[size]; empty = true; full = false; } /** * 返回队列长度 */ public int length() { return queue.length; } /** * 入队 */ public boolean in(Object obj) { if(isFull()) { System.out.println("Waring: In queue failed! queue is full!"); return false; } //设置当前队列入队节点为传入对象 queue[inIndex] = obj; //指向下一个节点 nextInIndex(); return true; } /** * 出队 */ public Object out() { if(isEmpty()) { System.out.println("Waring: Out queue failed! queue is empty!"); return null; } //获取当前出队节点的对象 Object result = queue[outIndex]; //清空当前位置 queue[outIndex] = null; //指向下一个节点 nextOutIndex(); return result; } /** * 是否为空 */ public boolean isEmpty() { if(inIndex == outIndex && queue[inIndex] == null) { return true; } return false; } /** * 是否已满 */ public boolean isFull() { if(inIndex == outIndex && queue[inIndex] != null) { return true; } return false; } //入队游标指向下一个节点 private int nextInIndex() { if(inIndex + 1 < queue.length) { inIndex += 1; } else { inIndex = 0; } return inIndex; } //出队游标指向下一个节点 private int nextOutIndex() { if(outIndex + 1 < queue.length) { outIndex += 1; } else { outIndex = 0; } return outIndex; } //测试 public static void main(String args[]) { CircularQueue test = new CircularQueue(4); test.in(1); test.in(2); test.in(3); test.in(4); test.in(5); System.out.println(test.out()); System.out.println(test.out()); System.out.println(test.out()); System.out.println(test.out()); System.out.println(test.out()); test.in(1); test.in(2); test.in(3); System.out.println(test.out()); System.out.println(test.out()); System.out.println(test.out()); } } |
随便看 |
|
百科全书收录4421916条中文百科知识,基本涵盖了大多数领域的百科知识,是一部内容开放、自由的电子版百科全书。