1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
front == tail 队列为空 当有元素入队的时候这时候tail ++ 当front == (tail + 1)%c 的时候对列满
public class LoopQueue<E> implements <E> { private E[] data; private int front ,tail; private int size; public LoopQueue(int capacity) { data = (E[])new Object[capacity+1]; front = 0; tail = 0; size = 0; } public LoopQueue() { this(10); } public int getCapacity() { return data.length - 1; } public boolean isEmpty() { return front == tail; } public int getSize() { return size; } public void enqueue(E e) { if((tail + 1) % data.length == front) { resize(getCapacity * 2); } data[tail] = e; tail = (tail + 1) % data.length; size ++; } public E dequeue() { if(isEmpty()) { throw new IllegalArgumentException("queue is empty"); } E ret = data[front]; data[front] = null; front = (front + 1) % data.length; size --; if(size == getCapacity() / 4 && getCapacity() / 2 != 0) { resize(getCapacity / 2); } return ret; } public E getFront() { if(isEmpty()) { return data[front]; } } private void resize(int newCapacity) { E[] newData = (E[])new Object[newCapacity + 1]; for(int i = 0;i < size; i ++) { newData[i] = data[(font+i) % data.length]; } tail = size; front = 0; data = newData; } }
|
近期评论