队列的一种实现:循环队列
队列的一种实现,循环队列,通过使用固定长度数组及首尾指针实现队列的入队、出队等:
class CircularQueue<T> { private Object[] data; //数据存储数组 private int head; //队列头指针 private int tail; //队列尾指针 private int size; //队列长度 /** * 初始化 * * @param k */ public CircularQueue(int k) { data = new Object[k]; //数组初始化 head = -1; tail = -1; size = k; } /** * 元素入队,成功则返回true,否则false * * @param value * @return */ public boolean put(T value) { if (isFull() == true) { //入队,判断队满 return false; } if (isEmpty() == true) { //入队,队空,则head置0 head = 0; } tail = (tail + 1) % size; //循环队列,队尾循环移动,所以使用取余的方式移动队尾 data[tail] = value; //将入队元素放入队列 return true; } /** * 出队 * * @return */ public T remove() { T result = null; if (isEmpty() == true) { //出队、判断队空 return result; } if (head == tail) { //队首 队尾重合,则当前队列只剩唯一元素 result = (T) data[tail]; head = -1; tail = -1; return result; } result = (T) data[head]; data[head] = null; head = (head + 1) % size; return result; } /** * 获取队首元素 * * @return */ public T head() { if (isEmpty() == true) { return null; } return (T) data[head]; } /** * 获取队尾元素 * * @return */ public T tail() { if (isEmpty() == true) { return null; } return (T) data[tail]; } /** 对空判断 * * @return */ public boolean isEmpty() { return head == -1; } /** 对满判断 * * @return */ public boolean isFull() { return ((tail + 1) % size) == head; //尾指针再移动一位则与头指针重合 } public String toString(){ StringBuilder str = new StringBuilder(); for (Object datum : data) { if (datum != null) { str.append(datum); } } return str.toString(); } public static void main(String[] args) { CircularQueue queue = new CircularQueue<Integer>(5); queue.put(5); queue.put(3); queue.put(1); System.out.println(queue); System.out.println(queue.head()); System.out.println(queue.tail()); queue.remove(); System.out.println(queue); System.out.println(queue.head()); System.out.println(queue.tail()); } }