[数据结构]手动实现队列

博客介绍了队列的两种实现方式,着重讲述用数组实现静态队列,且通常做成循环队列。指出循环队列中rear不指向最后有效元素的设计优势,还提到要将相关值限定在范围内,并给出一个关于rear下标的算法示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

队列有两种实现方式:静态队列(数组)和动态队列(链表)。

这次我就使用数组来实现静态队列了。值得注意的是:往往实现静态队列,我们都是做成循环队列。

 

package com.darrenchan;

public class MyQueue {
    public int[] arrays;
    public int front;//指向第一个有效元素
    public int rear;//指向最后一个有效元素的下一个元素(无效元素)

    public MyQueue(int[] arrays, int front, int rear) {
        this.arrays = arrays;
        this.front = front;
        this.rear = rear;
    }

    /**
     * 判断队列是否满了
     * @param myQueue
     * @return
     */
    public static boolean isFull(MyQueue myQueue){
        if((myQueue.rear + 1) % myQueue.arrays.length == myQueue.front){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 判断是否为空
     * @param myQueue
     * @return
     */
    public static boolean isEmpty(MyQueue myQueue){
        if(myQueue.rear == myQueue.front){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 入队
     * @param myQueue
     * @param value
     */
    public static void enQueue(MyQueue myQueue, int value){
        //不是满的队列才入队
        if(!isFull(myQueue)){
            myQueue.arrays[myQueue.rear] = value;
            myQueue.rear = (myQueue.rear + 1) % myQueue.arrays.length;
        }
    }

    /**
     * 遍历
     * @param myQueue
     */
    public static void traverse(MyQueue myQueue){
        int i = myQueue.front;
        while(i != myQueue.rear){
            System.out.print(myQueue.arrays[i] + " ");
            i = (i + 1) % myQueue.arrays.length;
        }
        System.out.println();
    }

    public static void outQueue(MyQueue myQueue){
        if(!isEmpty(myQueue)){
            int value = myQueue.arrays[myQueue.front];
            System.out.println(value);
            myQueue.front = (myQueue.front + 1) % myQueue.arrays.length;
        }
    }

    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue(new int[6], 0, 0);
        System.out.println(isEmpty(myQueue));
        enQueue(myQueue, 1);
        enQueue(myQueue, 2);
        enQueue(myQueue, 3);
        enQueue(myQueue, 4);
        enQueue(myQueue, 5);
        System.out.println(isFull(myQueue));
        traverse(myQueue);
        outQueue(myQueue);
    }
}

从上面的设计我们可以发现:rear并不指向最后一个有效的元素,在循环队列中这样设计是非常方便的!因为这样设计可以让我们分得清队头和队尾(不然循环队列不断入队或出队,位置是变化很快的)

由于我们是循环队列,所以frontrear值会经常变动,我们得把frontrear的值限定在一个范围内,不然会超出队列的长度的。

有这么一个算法:rear=(rear+1)%数组长度

  • 比如rear的下标是2,数组的长度是6,往后面移一位是3,那么rear = (rear+1) % 6,结果还是3

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值