队列是一种逻辑数据结构,代表的是先进先出的区域.就好像一个两端都是空的管子,一端用来进,一端用来出.和我们日常排队是一样的,出的一端代表商户,你只有到商户那边才能买东西,先到的先买.
用链表自己简单实现一个队列
public class MyLinkQueue<E> {
private Node<E> first;
private Node<E> last;
private Integer size = 0;
public MyLinkQueue() {
}
public boolean add(E o) {
Node<E> l = last;
Node<E> objectNode = new Node<>(o, l, null);
last = objectNode;
if (l == null) {
first = objectNode;
} else {
first.next = objectNode;
}
size++;
return true;
}
public Object poll() {
if (size == 0) {
throw new EmptyStackException();
}
E val = last.val;
Node previous = last.previous;
previous.next = null;
last = previous;
size--;
return val;
}
public Object peek() {
if (size == 0) {
throw new EmptyStackException();
}
return last.val;
}
public class Node<E> {
E val;
Node previous;
Node next;
Node () {
}
Node (E val) {
this.val = val;
}
Node (E val, Node previous, Node next) {
this.val = val;
this.previous = previous;
this.next = next;
}
}
}
两个链表的节点,分别代表头尾,然后在增删的时候维护好节点之间的关系就好了.
用数组自己简单实现一个队列
public class MyArrayQueue<E> {
private Object[] array;
private Integer addIndex;
private Integer pollIndex;
private Integer size;
public MyArrayQueue(Integer size) {
this.array = new Object[size];
this.addIndex = 0;
this.pollIndex = 0;
this.size = 0;
}
public boolean add(E o) {
//
if (size == array.length)
throw new ArrayIndexOutOfBoundsException();
array[addIndex] = o;
addIndex++;
if (addIndex == array.length)
addIndex = 0;
size++;
return true;
}
public Object poll() {
if (size == 0) {
throw new EmptyStackException();
}
Object o = array[pollIndex];
pollIndex++;
if (pollIndex == array.length)
pollIndex = 0;
size--;
return o;
}
public Object peek() {
if (size == 0) {
throw new EmptyStackException();
}
return array[pollIndex];
}
}
这里用一个固定长度的数组来实现队列,用两个指针分别代表数据进入时数组的索引和数据出去时数组的索引,为了防止维护两个指针之间的逻辑关系从而提高程序复杂度,所以加入size字段代表现在数组用了多少空间,只要size不为0,就能取数据,size不等于数组长度,就能塞数据.