java数组实现队列

时间:2023-03-09 03:48:45
java数组实现队列

数组队列

用数组实现的队列,也叫循环队列。就是定义一个数组,用两个下标head,tail表示队头和队尾。当队头和队尾相等时,队列为空。当队尾+1等于队头时,队列为满。

注意tail的值,当插入一个元素时tail=1 szie=1,两个时tail=2 size=2,三个时tail=0 size=3,四个时报错“is full”

package Algorithm;

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() {
return size() == length; } public boolean isEmpty() {
return size() == 0;
} public int size() {
if (queue[tail] != null && tail == head) {
return length;
} 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