【编程题】用数组实现队列(Java实现)

【编程题】用数组实现队列(Java实现)

题目要求

通过一个数组实现队列的功能,具有出队列、压队列、以及当前队列顶的元素等方法。
思路
在数组中用一个start指向当前队列头的位置,出队列就往上添加;用一个元素end表示队列尾的位置,入队列就往上添加。
代码

public class ArrayQueue {
    public static void main(String[] args){
        ArrayQueue queue=new ArrayQueue(3);
        queue.push(1);
        queue.push(3);
        queue.push(4);
        System.out.println(queue.peek());
        System.out.println(queue.pop());
        System.out.println(queue.pop());
        System.out.println(queue.pop());
       // System.out.println(queue.pop());
    }
    private int[] arr;
    private int start;
    private int end;
    private int size;
    public ArrayQueue(int initSize){
        if(initSize<0){
            throw new IllegalArgumentException("initSize must more than 0");
        }
        arr=new int[initSize];
        start=0;
        end=0;
        size=0;
    }
    public Integer peek(){
        if(size==0){
            return null;
        }
        return arr[start];
    }
    public void push(int val){
        if(size==arr.length){
            throw new ArrayIndexOutOfBoundsException("The queue is full");
        }
        size++;
        arr[end]=val;
        end=end==arr.length-1?0:end+1;


    }
    public Integer pop(){
        if(size==0){
            throw new ArrayIndexOutOfBoundsException("The queue is empty");
        }
        size--;
        int val=arr[start];
        start=start==arr.length-1?0:start+1;
        return val;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值