环形队列

王朝百科·作者佚名  2010-07-14
窄屏简体版  字體: |||超大  

实现方式,利用一个入队游标和一个出队游标来定制一个数组而构造一个环形队列:

(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());

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航