数组实现循环队列

循环队列

队列是一种先进先出的顺序存储结构,尾端进,头端出。这里我使用数组来实现循环队列的效果。

思路分析

首先定义一个数组,来存储数据。随后定义一个头指针front,指向队列的头元素;定义一个尾指针rear,指向待插入的位置,也就是队尾元素的后一个位置。 当头尾指针指向同一个位置时,即rear == front的时候,队列为空,这个好理解。当 (rear+1)%capacity == front时,队列为满。具体请看图解。

图解

在这里插入图片描述

线性看起来不直观,所以我又画了个环形的,请看下图。
在这里插入图片描述

代码实现

public class Test {
    private int[] arr;    // 数组实现循环队列
    private int front;    // 队列的头指针
    private int rear;     // 队列的尾指针
    private int capacity; // 队列的最大容量

    public Test(int capacity) {
        this.capacity = capacity;
        arr = new int[capacity];
    }

    public int deQueue() { //出队操作
        int value = arr[front];
        front = (front + 1) % capacity;
        return value;
    }

    public void enQueue(int ele) { //入队操作
        if (isFull()) {
            System.out.println("队列满,不能添加");
            return;
        }
        arr[rear] = ele;
        rear = (rear + 1) % capacity;
    }

    public boolean isFull() { //判断是否为满
        return (rear + 1) % capacity == front;
    }

    public boolean isEmpty() { //判断是否为空
        return rear == front;
    }

    public String toString() { //重写toString()方法
        if (isEmpty()) {
            return "队列为空,没有数据!";
        }
        StringBuilder sb = new StringBuilder();
        sb.append("队头\n");
        for (int x = front; x < front + getSize(); x++) {
            sb.append("arr[").append(x % capacity).append("]=").append(arr[x % capacity]).append("\n");
        }
        sb.append("队尾");
        return sb.toString();
    }


    public int getSize() { //获取队列中实际存储的位置
        return (rear - front + capacity) % capacity;
    }


    public static void main(String[] args) {
        Test test = new Test(4);
        test.enQueue(6); //入队
        test.enQueue(7);
        test.enQueue(8);
        System.out.println("***********入队后************");
        System.out.println(test);
        test.deQueue();//出队
        test.deQueue();
        System.out.println("***********出队后************");
        System.out.println(test);
        System.out.println("***********入队后************");
        test.enQueue(9);
        test.enQueue(10);
        System.out.println(test);
        test.deQueue();
        System.out.println("***********出队后************");
        System.out.println(test);
    }
}

在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值