[Java算法分析与设计]顺序循环队列的实现

先定义Queue接口

package com.chen.arithmetic_test.queue_test;

/**
 * Created by ChenMP on 2017/7/5.
 */
public interface Queue {
    //入队
    public void append(Object obj) throws Exception;
    //出队
    public Object delete() throws Exception;
    //获取头元素
    public Object getFront() throws Exception;
    //队列是否为空
    public boolean isEmpty();

}

书写实现类

package com.chen.arithmetic_test.queue_test;

/**
 * Created by ChenMP on 2017/7/5.
 * 顺序循环队列实现
 *  满足先进先出的实现
 *  顺序循环队列跟普通顺序队列的差别在于预防了假溢出的状态
 */
public class CircleSequenceQueue implements Queue {
    private Object[] queueData; //队列数组
    private int maxSize; //队列最大长度
    private int size; //队列大小
    private int rearIndex; //队尾位置
    private int frontIndex; //对首位置

    public CircleSequenceQueue() {
        this.maxSize = 10; //设置默认大小
        this.size = 0;
        this.rearIndex = 0;
        this.frontIndex = -1;
        this.queueData = new Object[maxSize];
    }

    public CircleSequenceQueue(int maxSize) {
        this.maxSize = maxSize;
        this.size = 0;
        this.rearIndex = 0;
        this.frontIndex = -1;
        this.queueData = new Object[maxSize];
    }

    @Override
    public void append(Object obj) throws Exception {
        if (size == maxSize)
            throw new Exception("队列已满!!!");

        this.queueData[rearIndex] = obj;
        this.rearIndex = rearIndex+1==this.maxSize?0:++rearIndex; //如果队列数组游标到了数组尾部,转至0位置
        this.size++;

    }

    @Override
    public Object delete() throws Exception {
        if (0 == size)
            throw new Exception("队列为空!!!");

        this.frontIndex = frontIndex+1==this.maxSize?0:++frontIndex; //如果队列数组游标到了数组尾部,转至0位置
        this.size--;
        return this.queueData[frontIndex];
    }

    @Override
    public Object getFront() throws Exception {
        if (0 == size)
            throw new Exception("队列为空!!!");
        int index = frontIndex+1==this.maxSize?0:frontIndex+1;
        return this.queueData[index];
    }

    @Override
    public boolean isEmpty() {
        return size>0?false:true;
    }
}

编写测试类

package com.chen.arithmetic_test.queue_test;

/**
 * Created by ChenMP on 2017/7/5.
 */
public class Test {
    public  static void main(String[] args) throws Exception {
        CircleSequenceQueue queue = new CircleSequenceQueue(12);

        for (int i=0; i<12; i++) {
            queue.append(i);
        }

        for (int i=0; i<3; i++) {
            System.out.print(queue.delete() + " ,");
        }

        System.out.println();

        queue.append(12);
        queue.append(12);
        queue.append(12);

        while (!queue.isEmpty()) {
            System.out.print(queue.delete() + " ,");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值