《数据结构》严蔚敏版(java解)——第三章 栈和队列03 顺序队列操作

来源:互联网 发布:c语言冒泡排序 编辑:程序博客网 时间:2024/05/21 17:16

概念:队列(queue)简称队,它同堆栈一样,也是一种运算受限的线性表,其限制是仅允许在表的一端进行插入,而在表的另一端进行删除。

特点:由于队列的插入和删除操作分别在队尾和队首进行,每个元素必然按照进入的次序离队,也就是说先进队的元素必然先离队,所以称队列为先进先出表(First  In First  Out,简称FIFO)。

代码实现

package csdn.wj.assistant;public interface Queue {public class QueueEmptyException extends RuntimeException {public QueueEmptyException(String err) {super(err);}}// 返回队列的大小public int getSize();// 判断队列是否为空public boolean isEmpty();// 数据元素 e入队public void enqueue(Object e);// 队首元素出队public Object dequeue() throws QueueEmptyException;// 取队首元素public Object peek() throws QueueEmptyException;}package csdn.wj.linear;import csdn.wj.assistant.Queue;public class Queue01 implements Queue {private static final int CAP = 7;//队列默认大小private Object[] elements;private int capacity;private int front;private int rear;//数据元素数组//数组的大小  elements.length//队首指针,指向队首//队尾指针,指向队尾后一个位置public Queue01() {this(CAP);}public Queue01(int cap){capacity = cap + 1;elements = new Object[capacity];front = rear = 0;}//返回队列的大小 public int getSize() {return (rear -front+ capacity)%capacity;}//判断队列是否为空public boolean isEmpty() {return front==rear;}//数据元素 e入队public void enqueue(Object e) {if (getSize()==capacity-1) expandSpace();elements[rear] = e;rear = (rear+1)%capacity;}private void expandSpace(){Object[] a = new Object[elements.length*2];int i = front;    int j = 0;while (i!=rear){    //将从 front开始到  rear前一个存储单元的元素复制到新数组a[j++] = elements[i];i = (i+1)%capacity;}elements = a;capacity = elements.length;front = 0;rear = j;   //设置新的队首、队尾指针}//队首元素出队public Object dequeue() throws QueueEmptyException {if (isEmpty())throw new QueueEmptyException("错误:队列为空");Object obj = elements[front];elements[front] = null;front = (front+1)%capacity;return obj;}//取队首元素public Object peek() throws QueueEmptyException {if (isEmpty())throw new QueueEmptyException("错误:队列为空");return elements[front];}}


0 0