package com.yin.test;
public class ArrayQueue {
private int size;
private int[] array;
public int head = 0;
public int tail = 0;
public ArrayQueue(int size) {
this.size = size;
array = new int[size];
}
public void Add(int addNum) {
if (!isFull()) {
tail = (tail -1 + this.size)%this.size;
array[tail] = addNum;
} else {
System.out.println("队列已满,不能进行插入操作");
}
}
public void del() {
if (!isEmpty()) {
//tail--
array[head] = 0;
head = (head -1 + this.size)%this.size;
} else {
System.out.println("队列为空不能进行删除操作");
}
}
public boolean isFull() {
int pos = (tail -1 + this.size)%this.size;
if (pos == head) {
return true;
} else {
return false;
}
}
public boolean isEmpty() {
if (head == tail)
return true;
else
return false;
}
public void listElements() {
//从尾部到头部输出队列元素
int low = tail;
int high = head;
while (low != high) {
System.out.print(array[low] + ",");
low++;
}
}
public static void main(String args[]) {
ArrayQueue queue = new ArrayQueue(5);
System.out.println("queue.isEmpty() = " + queue.isEmpty());
queue.Add(1);
System.out.println("head = " + queue.head);
System.out.println("tail = " + queue.tail);
queue.Add(2);
queue.Add(3);
queue.del();
System.out.println("head = " + queue.head);
System.out.println("tail = " + queue.tail);
queue.Add(4);
queue.Add(5);
System.out.println("head = " + queue.head);
System.out.println("tail = " + queue.tail);
queue.Add(6);
queue.listElements();
}
}
java数组实现队列操作
最新推荐文章于 2023-01-12 13:15:09 发布