public class ArrayQueue {
private String[] items;
private int n;
private int head;
private int tail;
public ArrayQueue(int n) {
this.n = n;
items = new String[n];
head = tail = 0;
}
public String out() {
if (head == n - 1) {
String item = items[head];
head = tail = 0;
return item;
} else if (head == tail) {
return null;
} else {
return items[head++];
}
}
public boolean in(String item) {
if (tail <= n - 1) {
items[tail++] = item;
return true;
}
if (head == 0) {
return false;
}
rebuild();
items[tail++] = item;
return true;
}
private void rebuild() {
int index = head;
for (int i = 0; i < tail - head; ++i) {
items[i] = items[index++];
}
tail = tail - head;
head = 0;
}
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(6);
System.out.println(arrayQueue.out());
arrayQueue.in("qyd");
arrayQueue.in("qyj");
arrayQueue.in("qgl");
arrayQueue.in("qyx");
arrayQueue.in("hcy");
arrayQueue.in("qfl");
System.out.println(arrayQueue.in("xxx"));
System.out.println(arrayQueue.out());
arrayQueue.in("xxx");
System.out.println(arrayQueue.out());
System.out.println(arrayQueue.out());
System.out.println(arrayQueue.out());
System.out.println(arrayQueue.out());
System.out.println(arrayQueue.out());
System.out.println(arrayQueue.out());
System.out.println(arrayQueue.out());
}
}
java用数组实现队列,可以rebuild
猜你喜欢
转载自blog.csdn.net/weixin_42002747/article/details/103524752
今日推荐
周排行