队列(queue)简介
先进先出线性表,有俩个操作入队(enqueue)和出队(dequeue)。
队列的作用
- 网络通讯
- 进程间信息交流
链表实现
链表实现对于java来说比较简单,就不写了。
顺序实现
此方法参考自大话数据结构循环队列实现方法
原理说明
初始化
刚开始的front 和back 都为0.队列为空。
当出现这样的情况是队列为满。
也就是说在满的时候的数组会有一个空位。
判断满的条件为
(back + 1) % QueueSize == front
例如 ( 1+ 1)% 5 = 2
具体实现
public class MyQueue<AnyType> {
private int DEFAULT_CAPACITY;
private int currentSize;
private int front;
private int back;
public AnyType [] theItems;
//初始化
public MyQueue(int DEFAULT_CAPACITY) {
clear( DEFAULT_CAPACITY );
}
//初始化队列
public void clear (int number) {
DEFAULT_CAPACITY = number + 1 ;
theItems = (AnyType[]) new Object[DEFAULT_CAPACITY];
currentSize = 0;
front = 0;
back = 0;
}
//返回现在的队列有几个在排队
public int size() {
return currentSize;
}
//队列为空返回true,否则返回false
public boolean isEmpty() {
return size() == 0;
}
//入队
public void enqueue( AnyType value ) {
if ( (back + 1) % DEFAULT_CAPACITY == front) {
System.out.println("队列已满");
}
theItems[back] = value;
back = (back + 1) % DEFAULT_CAPACITY;
currentSize++;
}
//出队
public AnyType dequeue( ) {
if (isEmpty()) {
System.out.println("队列为空");
}
AnyType topValue = theItems[front];
front = (front + 1) % DEFAULT_CAPACITY;
currentSize--;
return topValue;
}
}
测试代码
public static void main(String[] args) {
MyQueue test = new MyQueue(4);
test.enqueue(10);
test.enqueue(11);
test.enqueue(12);
System.out.println(test.dequeue());
test.enqueue(13);
System.out.println(test.dequeue());
test.enqueue(14);
System.out.println(test.dequeue());
System.out.println(test.dequeue());
}
运行结果
10
11
12
13
写法分析
这种写法浪费了一个内存空位。