手写扩容队列
public static class ArrayQueue {
int n;
int tail = 0;
int head = 0;
String[] queue;
public ArrayQueue(int capacity) {
this.n = capacity;
queue = new String[capacity];
}
public void enqueue(String s) {
if (tail == n) {
String[] temp = new String[(int) (1.5 * queue.length)];
for (int i = 0; i < queue.length; i++) {
temp[i] = queue[i];
}
queue = temp;
}
queue[tail] = s;
tail ++;
}
public String dequeue() {
if (head == tail){
return null;
}
else{
String ret = queue[head];
head ++;
return ret;
}
}
}
循环队列一:数据搬移类型
public static class CycleQueue {
String[] queue;
int n;
int head;
int tail;
public CycleQueue(int n) {
this.n = n;
queue = new String[n];
}
public boolean enqueue(String s) {
if (tail == n) {
if (head == 0) {
return false;
}
for(int i = head ; i < tail ; i ++){
queue[i-head] = queue[i];
}
tail = tail - head;
head = 0;
}
queue[tail] = s;
tail++;
return true;
}
public String dequeue() {
if (head == tail) {
return null;
}
String res = queue[head];
head++;
return res;
}
}
循环队列二:循环head/tail
重点:确定好队空和队满的判定条件
这里,浪费了数组的一个存储空间,作为队满队空的判断条件。
public static class CycleQueue2{
String[] queue;
int n;
int head;
int tail;
public CycleQueue2(int n) {
this.n = n;
queue = new String[n];
}
public boolean enqueue(String s) {
if ((tail + 1) % n == head) {
return false;
}
queue[tail] = s;
tail = (tail + 1) % n;
return true;
}
public String dequeue() {
if(tail == head){
return null;
}
String res = queue[head];
head = (head + 1) % n;
return res;
}
}
链式队列
public static class LinkQueue{
Queue head ;
Queue prev;
public void enqueue(String s){
Queue queue = new Queue();
queue.data = s;
if (prev != null) {
prev.next = queue;
prev = queue;
} else {
prev = queue;
head = queue;
}
}
public String dequeue() {
if (head != null) {
String res = head.data;
if (head.next != null) {
head = head.next;
} else {
head = null;
}
return res;
}
return null;
}
}
public static class Queue{
public String data;
public Queue next;
public String toString() {
return data;
}
}