Java实现数据结构与算法之队列

队列(先进先出)

循环队列

public class MyQueue {
    private int[] queArray;
    private int front;
    private int rear;
    private int length;
    private int maxSize;

    public MyQueue(int queueSize){
        maxSize = queueSize;
        queArray = new int[queueSize];
        front = 0;
        rear = -1;
        length = 0;
    }

    public void push(int elem){
        if (isFull()) {
            throw new RuntimeException("队列已满");
        }
        if (rear == maxSize-1) {
            rear = -1;
        }
        queArray[++rear] = elem;
        length++;
    }

    public int pop(){
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        int elem = queArray[front++];
        if (front == maxSize) {
            front = 0;
        }
        length--;
        return elem;
    }

    public int peak(){
        if (length == 0) {
            throw new RuntimeException("队列为空");
        }
        return queArray[front];
    }

    public boolean isEmpty() {
        return length == 0;
    }

    public boolean isFull(){
        return length == maxSize;
    }
}

实例结果

在这里插入图片描述
在这里插入图片描述

优先级队列

public class PriorityQueue {
    private int[] queArray;
    private int maxSize;
    private int referencePoint;
    private int length;

    public PriorityQueue (int maxSize , int referencePoint) {
        this.maxSize = maxSize;
        this.referencePoint = referencePoint;
        queArray = new int[maxSize];
        length = 0;
    }

    public void push(int elem) {
        if (isFull()) {
            throw new RuntimeException("队列已满");
        }

        if (isEmpty()) {
            queArray[length++] = elem;
        } else {
            int i;
            for (i=length;i>0;i--) {
                int dis = Math.abs(elem - referencePoint);
                int cur = Math.abs(queArray[i-1] - referencePoint);
				//根据与相对值的绝对值大小决定在队列中的位置
                if (dis >= cur) {
                    queArray[i] = queArray[i-1];
                } else {
                    break;
                }

            }
            queArray[i] = elem;
            length++;
        }
    }

    public int pop(){
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        int elem = queArray[--length];
        return elem;
    }

    public int peak() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        return queArray[length - 1];
    }

    public boolean isEmpty() {
        return length == 0;
    }

    public boolean isFull() {
        return length == maxSize;
    }
}

实例结果

在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值