地主_的博客

沉稳,冷静,向上,热爱

[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() + " ,");
        }
    }
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27832191/article/details/74452061
文章标签: java java算法
想对作者说点什么? 我来说一句

数据结构实现顺序循环队列

2014年09月16日 2KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭