[數據結構]-數組實現隊列(普通)數組
1 首指針數據結構
2 尾指針app
不是循環隊列,將前方空出來的位置,依次向前移動ide
package com.cn.jichu.day09; public class Queue<E> { /** * 數組 */ private E[] data; /** * 首指針 */ private int head; /** * 尾指針 */ private int tail; /** * 當前隊列大小 */ private int size; public Queue(int size) { data = (E[]) new Object[size]; this.size = size; } public void enqueue(E e){ if(tail == size){ //當尾部滿了,頭未移動那麼說明滿了 if(head == 0){ throw new IllegalArgumentException("當前隊列滿了"); }else{ //頭移動了,說明前方有位置 //一下操做,爲向前移動 for(int i = head;i<tail;i++){ data[i - head] = data[i]; } tail = tail - head; head = 0; } } data[tail] = e; tail ++; } public E dequeue(){ if(head == tail){ throw new IllegalArgumentException("當前隊列沒有元素能夠出列了"); } E e = data[head]; data[head] = null; head ++; return e; } @Override public String toString(){ StringBuilder ret = new StringBuilder(); ret.append("queue head["); for(int i=0;i<data.length;i++){ ret.append(data[i] + " "); } ret.append(" ] tail"); return ret.toString(); } }