/**
* 是否为空队列
* @return
*/
public boolean isEmpty();
/**
* 队列长度
* @return
*/
public int getSize();
/**
* 队头,数据不出对
* @return
*/
public Object index();
/**
* 对尾,数据不出对
* @return
*/
public Object last();
/**
* 入队
* @param o
* @return
*/
public boolean push(Object o);
/**
* 出对
* @return
*/
public Object pop();
}
public class LinkedQueueImpl implements Queue {
private Note root;
private Note end;
private int size;
public boolean isEmpty() {
return size == 0l;
}
public int getSize() {
return size;
}
public Object index() {
return root;
}
public Object last() {
return end;
}
public boolean push(Object o) {
if (!validate(o))
throw new NullPointerException("the element can't be null");
Note note = new Note(o);
if (null == end) {
end = note;
root = note;
} else {
end.next = note;
end = note;
}
size++;
return true;
}
private boolean validate(Object o) {
if (null == o)
return false;
return true;
}
public Object pop() {
if (null != root) {
try {
return root.value;
} finally {
root = root.next;
size--;
}
}
return null;
}
private class Note {
private Note next;
private Object value;
private Note(Object o) {
this.value = o;
}
}
}
public class ArrayQueueImpl implements Queue {
public ArrayQueueImpl(int size) {
this.data = new Object[size];
}
public ArrayQueueImpl() {
this(8);
}
private int first;
private int last;
private Object[] data;
public boolean isEmpty() {
return first == last;
}
public int getSize() {
if (last >= first)
return last - first;
else
return data.length - first + last;
}
public Object index() {
return data[first];
}
public Object last() {
if (last > 0)
return data[last - 1];
else
return data[data.length - 1];
}
public boolean push(Object o) {
if (null == o)
throw new NullPointerException("element can't be null");
if (this.getSize() < data.length-1) {
data[last] = o;
if (last < data.length - 1) {
last++;
} else {
last = 0;
}
} else {
increase();
data[last++] = o;
}
return true;
}
private synchronized void increase() {
Object[] newData = new Object[data.length << 1];
if (last > first) {
System.arraycopy(data, first, newData, 0, this.getSize());
} else {
System.arraycopy(data, first, newData, 0, data.length - first);
System.arraycopy(data, 0, newData, data.length - first, last);
}
data = newData;
last = this.getSize();
first = 0;
}
public Object pop() {
if (!this.isEmpty()) {
try {
return data[first];
} finally {
if (first == data.length - 1)
first = 0;
else
first++;
}
}
return null;
}
}