java实现数组模拟队列



/*
利用数组实现队列,对队列中值进行增加查询
 */
public class TestQueue01 {
    public static void main(String[] args) {
    //演示代码
        ArrayQueue arrayQueue = new ArrayQueue();
        arrayQueue.iniQueue(3);
        arrayQueue.addQueue(4);
        arrayQueue.addQueue(5);
        arrayQueue.addQueue(6);
        arrayQueue.showQueue();
        arrayQueue.addQueue(7);
        arrayQueue.getQueue();
        arrayQueue.showQueue();

    }

}
//初始化队列

class ArrayQueue {
    int arr[];
    int maxSize;
    int front;
    int rear;

//初始化数组
    public void iniQueue(int length) {
        arr = new int[length];
        maxSize = arr.length;//找到数列的最大长度
        front = -1;//指向队列头的前一个位置
        rear = -1; //定义初始的尾指针
    }

    public boolean isFull() { //判断数组是否满
        return maxSize - 1 == rear;
    }

    public boolean isEmpty(){//判断数组是否为空
        return rear == front;
    }
    // 向数组中加入数据
    public void addQueue(int element) {
        if (isFull()) {
            System.out.println("已满,放入失败");
            return;
        }
        rear++;//指针后移动
        arr[rear] = element;

    }
    //从数组中取出数据
    public int getQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空 无法取出");
        }
        front++; //front后移
        int temp = arr[front];
        arr[front] = 0;//恢复默认值
        return temp;
    }
    //用于显示的输出队列
    public void showQueue(){
        String s = Arrays.toString(arr);
        System.out.println(s);
    }

}

这种队列的缺点是容易造成假溢出,队列并没有真正的满.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值