数据结构之基于Java的顺序队列实现

本文的代码来自于《数据结构与算法(JAVA语言版)》,是笔者在网上找到的资料,非正式出刊版物。笔者对代码一些比较难以理解的部分添加了注释和图解,欢迎大家来讨论。
重点理解通过取余运算将线性数组转换为循环数组

public class QueueArray implements Queue {
    private static final int CAP = 7;//队列默认大小
    private Object[] elements;  //数据元素数组
    private int capacity;       //数组的大小elements.length
    private int front;          //队首指针,指向队首
    private int rear;           //队尾指针,指向队尾后一个位置
    public QueueArray() {
        this(CAP);
    }
    public QueueArray(int cap){
        capacity = cap + 1;
        elements = new Object[capacity];
        front = rear = 0;
    }

    public int getSize() {
        return (capacity-front+rear)%capacity;
    }//返回队列的大小

    public boolean isEmpty() {
        return front==rear;
    }//判断队列是否为空

    public void enqueue(Object e) {
        if (getSize()==capacity-1) expandSpace();
        elements[rear] = e;
        rear = (rear+1)%capacity;
    }//数据元素e入队

    private void expandSpace(){
        Object[] a = new Object[elements.length*2];
        int i = front;
        int j = 0;
        while (i!=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];
    }   
}

package dsa.adt;

import dsa.exception.QueueEmptyException;

public interface Queue {
    //返回队列的大小
    public int getSize();

    //判断队列是否为空
    public boolean isEmpty();

    //数据元素e入队
    public void enqueue(Object e);

    //队首元素出队
    public Object dequeue() throws QueueEmptyException;

    //取队首元素
    public Object peek() throws QueueEmptyException;
}


public class QueueEmptyException extends RuntimeException {

    public QueueEmptyException(String err) {
        super(err);
    }   
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值