数据结构与算法_队列_03

题记

队列也可以用数组来实现,不过这里有个问题,当数组下标满了后就不能再添加了,但是数组前面由于已经删除队列头的数据了,导致空。所以队列我们可以用循环数组来实现,见下面的代码:

/**
 * 队列 先进先出
 * @author fancy
 * @date 2018-12-05 17:13
 */
public class ArrayQueue {

    private int[] array;

    private int nItem;

    private int size;

    private int frontIndex;

    private int rearIndex;

    public ArrayQueue (int size) {
        this.array = new int[size];
        this.size = size;
        this.nItem = 0;
//        头部
        this.frontIndex= 0;
//        尾部
        this.rearIndex = 0;
    }

    /**
     * @author fancy
     */
    public void insert (int value) {
        if (isFull()) {
            throw new OutOfMemoryError();
        }
        //取余,轮循
        rearIndex = ++rearIndex % size;
        array[rearIndex] = value;
        nItem ++ ;
    }

    public int remove () throws Exception {
        if(isEmpty()){
            throw new Exception("队列为空");
        }
        frontIndex = ++frontIndex % size;
        nItem --;
        return array[frontIndex];
    }

    public int peek () {
        return array[frontIndex];
    }

    private boolean isEmpty () {
        if (nItem == 0) {
            return true;
        }
        return false;
    }

    private boolean isFull () {
        if (nItem == size){
            return true;
        }
        return false;
    }
}
/**
 * 先进后出
 * 链表实现
 * 链表结构添加在尾部添加,去除只要吧头部去除就可以了
 * @author fancy
 * @date 2018-12-05 17:54
 */
public class LinkedQueue {

    private MyLinkedList list;

    public LinkedQueue() {
        this.list = new MyLinkedList();
    }

    public void insert (int value) {
        list.add(list.getSize(), value);
    }

    /**
     * 删除第一个
     */
    public int remove () {
        return list.remove(0);
    }

    public int peek () {
        return list.get(0);
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值