As we all know, the queue is FIFO. So if I take a single element out of the head of the queue first, the inside of the queue moves each of the following tables of the array down one bit. If this queue is millions, then you can imagine how this performance is a sore egg. Let's take a different mindset to solve this problem:
I make this array a closed loop. That is, after I remove the head element of the queue, I do not move the position but leave it blank. The original second element is then marked with a bit-head element (subscript is not moved). If another element enters, the element is placed in the empty space of the array. Of course, if the array is not filled, then fill in the blanks, then fill in the blank elements left by the pop.
In this way, we put an array into a closed loop, without moving the elements of the subscript can also be done for other advanced first out, see the code:
Package test;public class queue {public static void main (String[] args ) {queue st = new queue (+); for (int i = 0; i < 98; i++) {st.push (i);} System.out.println ("pop first==" +st.pop ()); St.push (Wuyi); St.push (n); St.push (+); while (St.size () > 0) {object dt = st.pop (); if (dt != null) {system.out.println (" Data= "+dt);}}} private int size = 0;private int capacity;private object[] data; private int currhead = 0;private int max_size = integer.max_value; Private int currindex = 0;public queue (int capacity) {data = new object[capacity];this.capacity = capacity;} Public int size () {return size;} Public void push (object obj) {if (size > max_size) {thRow new illegalargumentexception ("Over max size ..."); if (size <= capacity) {if (currhead == 0) { //if no pops have been data[ Size++] = obj;} else{if (capacity - currhead == size) { //if the queue is full data[currindex++] = obj;size++;} else {data[++size] = obj;}}}} Public object pop () {--size;if (size >= 0) {if (currhead == capacity) {currhead = 0;} Object value = data[currhead];d Ata[currhead] = null;currhead++;return value;} Return null;}}
Java uses closed-loop arrays to customize high-performance queues