使用数组实现固定长度的队列结构,很多人coding时,都会使用两个变量start和end作为指针,来表示队列的头和尾,然后判断end大于start,start一直追赶end的这种方式实现,这其中有些边界条件判断来判断去,end到达尾部然后回到头部,end又小于start等等情况。coding起来比较复杂。
我的实现呢,再添加一个变量size,用来表示当前队列还有几个元素,只要size大于数组长度就不能再入队,size小于0就不能再出队列了。
入队列规则:移动end变量,每次让end变量指向队列尾部的下一个位置,每次入队列时只用把元素放入到end的位置。如果到达数组尾部,但是队列并没有满(size不大于数组长度),那么让end等于0,继续循环。当然,size要加加
出队列规则:移动start变量,每次start变量就指向队列的头部,出队列时,就取出start变量位置的元素,start加加,当start到达数组尾部,但是队列并没有空(size不小于0),则让start回到数组首部,即start等于0,继续循环。当然,size要减减
代码:
public class UsingArrayRealizeQueue { int[] queue = new int[5]; int size = 0;// 表示队列中还有几个元素 int start =0;// 指向队列头 int end = 0;// 指向队列尾 // 入队列 public void put(int value){ if(size >= queue.length){ throw new ArrayIndexOutOfBoundsException("the size more than bounds"); } queue[end++] = value; size++; if(end == queue.length){// 到达数组尾部,但是数组并没有满,再回到数组头部继续循环 end = 0; } } // 出队列 public int poll(){ if(size <= 0){ throw new IllegalArgumentException("the size less than 0"); } if(start == queue.length){// 到达数组尾部,但是数组并没有空,再回到数组头部继续循环 start = 0; } size--; return queue[start++]; } public static void main(String[] args) { UsingArrayRealizeQueue queue = new UsingArrayRealizeQueue(); queue.put(1); queue.put(2); queue.put(3); queue.put(4); queue.put(5); System.out.println(queue.poll());// 1 System.out.println(queue.poll());// 2 queue.put(6); queue.put(7); System.out.println(queue.poll());// 3 System.out.println(queue.poll());// 4 System.out.println(queue.poll());// 5 System.out.println(queue.poll());// 6 queue.put(8); System.out.println(queue.poll());// 7 System.out.println(queue.poll());// 8 // System.out.println(queue.poll()); } }
测试结果: