队列是一种只允许在表的前端进行删除操作且在表的后端进行插入操作的线性表。其中,执行插入操作的端叫作队尾,执行删除操作的端叫作队头。没有元素的队列叫作空队列,在队列中插入一个队列元素叫作入队,从队列中删除一个队列元素叫作出队。因为队列只允许在队头插入,在队尾删除,所以最早进入队列的元素将最先从队列中删除,所以队列又叫先进先出(FIFO-first in first out)线性
实现一个队列
add():向队列的尾部加入一个元素(入队),先入队列的元素在最前面
poll():删除头部的元素,出队列
peek():取出头部的队列元素
代码实现
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 public class Queue <E > { private Object[] data = null ; private int maxSize = 0 ; private int front; private int rear; Queue () { this (10 ); } Queue (int initial){ if (initial >= 0 ){ this.maxSize = initial; data = new Object [initial]; front = rear = 0 ; }else { throw new RuntimeException ("Queue can't be empty'" + initial); } } public boolean add ( E e){ if (rear == maxSize){ throw new RuntimeException ("Queue is full cannot add more" ); }else { data[rear++] = e; return true ; } } public E poll (){ if (empty ()) { throw new RuntimeException ("QueueNullException" ); }else { E value = (E) data[front]; data[front++] = null ; return value; } } private boolean empty () { return maxSize == 0 ; } public E peek () { if (empty ()){ throw new RuntimeException ("QueueNullException" ); }else { return (E) data[front]; } }