通过数组实现队列

数组实现队列

实现方法与栈相同,不过队列是先进后出。

队列代码

package com.wuxudong.queue;

//通过数组实现队列
public class MyQueue {

    private int [] arr;

    public MyQueue(){
        arr=new int [0];
    }

    //添加方法
    public void add(int element){

        //创建一个新数组
        int [] newArr=new int [arr.length+1];

        //将原数组复制给新数组
        System.arraycopy(arr,0,newArr,0,arr.length);

        //将元素添加到新数组中
        newArr[arr.length]=element;

        //将新数组的引用赋值给老数组
        arr=newArr;

    }

    //取出并删除元素的方法
    public int poll(){
        if (arr.length==0){
            throw new RuntimeException("队列的长度为0");
        }

        //定义返回的元素
        int element=0;


        //创建一个新数组
        int [] newArr=new int[arr.length-1];

        //将原数组赋值给新数组
        System.arraycopy(arr,1,newArr,0,arr.length-1);

        //获取返回的元素
        element=arr[0];

        //将新数组赋值给原数组
        arr=newArr;

        return element;

    }

    //获取队列的第一个元素
    public int getElement(){
        if (arr.length==0){
            throw new RuntimeException("队列为空");
        }

        return arr[0];
    }

    //判断队列是否为空
    public boolean isEmpty(){
        return arr.length==0;
    }





}

测试代码

package com.wuxudong.queue;

public class MyQueueTest {

    public static void main(String[] args) {
        MyQueue myQueue=new MyQueue();
        //进入队列
        myQueue.add(1);
        myQueue.add(2);
        myQueue.add(3);

        //获取队列的第一个元素
        System.out.println(myQueue.getElement());

        //出列
        System.out.println(myQueue.poll());
        System.out.println(myQueue.poll());
        System.out.println(myQueue.poll());

        //是否为空
        System.out.println(myQueue.isEmpty());


    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值