题记
队列也可以用数组来实现,不过这里有个问题,当数组下标满了后就不能再添加了,但是数组前面由于已经删除队列头的数据了,导致空。所以队列我们可以用循环数组来实现,见下面的代码:
/**
* 队列 先进先出
* @author fancy
* @date 2018-12-05 17:13
*/
public class ArrayQueue {
private int[] array;
private int nItem;
private int size;
private int frontIndex;
private int rearIndex;
public ArrayQueue (int size) {
this.array = new int[size];
this.size = size;
this.nItem = 0;
// 头部
this.frontIndex= 0;
// 尾部
this.rearIndex = 0;
}
/**
* @author fancy
*/
public void insert (int value) {
if (isFull()) {
throw new OutOfMemoryError();
}
//取余,轮循
rearIndex = ++rearIndex % size;
array[rearIndex] = value;
nItem ++ ;
}
public int remove () throws Exception {
if(isEmpty()){
throw new Exception("队列为空");
}
frontIndex = ++frontIndex % size;
nItem --;
return array[frontIndex];
}
public int peek () {
return array[frontIndex];
}
private boolean isEmpty () {
if (nItem == 0) {
return true;
}
return false;
}
private boolean isFull () {
if (nItem == size){
return true;
}
return false;
}
}
/**
* 先进后出
* 链表实现
* 链表结构添加在尾部添加,去除只要吧头部去除就可以了
* @author fancy
* @date 2018-12-05 17:54
*/
public class LinkedQueue {
private MyLinkedList list;
public LinkedQueue() {
this.list = new MyLinkedList();
}
public void insert (int value) {
list.add(list.getSize(), value);
}
/**
* 删除第一个
*/
public int remove () {
return list.remove(0);
}
public int peek () {
return list.get(0);
}
}