algo/java/09_queue/DynamicArrayQueue.java
2018-10-10 23:06:56 +08:00

57 lines
1.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package queue;
/**
* Created by wangzheng on 2018/10/9.
*/
public class DynamicArrayQueue {
// 数组items数组大小n
private String[] items;
private int n = 0;
// head表示队头下标tail表示队尾下标
private int head = 0;
private int tail = 0;
// 申请一个大小为capacity的数组
public DynamicArrayQueue(int capacity) {
items = new String[capacity];
n = capacity;
}
// 入队操作将item放入队尾
public boolean enqueue(String item) {
// tail == n表示队列末尾没有空间了
if (tail == n) {
// tail ==n && head==0表示整个队列都占满了
if (head == 0) return false;
// 数据搬移
for (int i = head; i < tail; ++i) {
items[i-head] = items[i];
}
// 搬移完之后重新更新head和tail
tail -= head;
head = 0;
}
items[tail] = item;
tail++;
return true;
}
// 出队
public String dequeue() {
// 如果head == tail 表示队列为空
if (head == tail) return null;
// 为了让其他语言的同学看的更加明确,把--操作放到单独一行来写了
String ret = items[head];
++head;
return ret;
}
public void printAll() {
for (int i = head; i < tail; ++i) {
System.out.print(items[i] + " ");
}
System.out.println();
}
}