java数组实现队列

Posted pu20065226

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java数组实现队列相关的知识,希望对你有一定的参考价值。

 

package
Algorithm; /** * @author [email protected]</br> Created By: 2019-1-22 下午2:41:32 */ public class QueueByArray { private Object[] queue; final static int DEFAULT_MAX_SIZE = 100; int length, head, tail; private void init() { queue = new Object[length]; head = tail = 0; } QueueByArray() { length = DEFAULT_MAX_SIZE; init(); } QueueByArray(int size) { length = size; init(); } public boolean isFull() { if (queue[tail] != null) {// exclude the inition status return tail % length == head;// tail++ when put } return false; } public boolean isEmpty() { if (queue[tail] != null) {// exclue the full status return false; } return tail == head;// head ++ when got } public int size() { if (isFull()) { return length; } if (isEmpty()) { return 0; } return (tail - head + length) % length; } public void clear() { queue = null; queue = new Object[length]; } // in queue public void put(Object o) throws Exception { if (isFull()) { System.out.println(head); System.out.println(tail); throw new Exception("the queue is full!"); } else { queue[tail] = o; tail = (tail + 1) % length; } } // out queue public Object get() throws Exception { if (isEmpty()) { throw new Exception("the queue is empty!"); } else { final Object o = queue[head]; queue[head] = null; head = (head + 1) % length; return o; } } public static void main(String[] args) throws Exception { final QueueByArray myqueue = new QueueByArray(3); for (int i = 111; i < 114; i++) { myqueue.put(i); } System.out.println("head==" + myqueue.head + ";tail==" + myqueue.tail + ";size==" + myqueue.size()); while (myqueue.size() > 0) { System.out.println(myqueue.get()); } } }


输出:

head==0;tail==0;size==3
111
112
113

 






以上是关于java数组实现队列的主要内容,如果未能解决你的问题,请参考以下文章

Java数组实现队列

Java数组实现队列

Java数据结构-队列

用java实现循环队列?

java 数据结构 用数组实现队列

perl中的队列