数据结构与算法-基础数据结构:队列实现

在学习队列的实现过程中,跟着教程自己手写了队列的实现,理解队列的先进先出原理。以及略微复杂的循环队列形成的一个闭环,略微吃力,还需努力,详细说明在注释

package com.zhouyou.queue;
// 普通队列的实现
public class ArrayQueue {

    private int head; // 头
    private int tail; // 尾
    private int[] date; // 头
    private int size; // changdu
    private int n; // 数组的大小 最大的空间

    public ArrayQueue(int cap){
        date = new int[cap];
        n = cap;//初始化
    }

    public void push(int m){
        //判断我们这个队列是不是已经满了
        if(tail == n){
            // 移动 或者扩容,为了节约性能是移动 时间复杂度n-1 之前都是o(1)
            return;
        }
        date[tail] = m;
        tail++;
    }

    public int pop(){
        //出队列 1 2 3 4 5 O(1) 很大的空间浪费 判断空
    if (isEmpty()){
        return -1;
    }
    // 先进先出 每次都是从头开始弹
    int m = date[head];
    head ++;
    return m;
    }

    private boolean isEmpty(){
        return head == tail;
    }
    public static void main(String[] args) {
        ArrayQueue arrayQueue = new ArrayQueue(5);
        arrayQueue.push(1);
        arrayQueue.push(2);
        arrayQueue.push(3);
        arrayQueue.push(4);
        arrayQueue.push(2);
        int[] date = arrayQueue.date;
        for (int i : date) {
            System.out.println(i);
            int pop = arrayQueue.pop();
            System.out.println("弹出来的是: "+ pop);
        }
    }
}

下面是循环队列的实现

package com.zhouyou.queue;

public class CircleArrayQueue {
    private int data[];		// 数据
    private int head = 0;		//头
    private int tail = 0;		//尾
    private int n = 0;		//数组的大小 最大的空间
    private int size;		//当前已经存了几个数了

    public CircleArrayQueue(int cap){
        data = new int[cap];
        n = cap;
    }
    public void push(int m){
        // 判断 队列 是否 满了 用取模 是防止 0 1 等情况
        if((tail + 1) % n == head){
            return ;
        }
        data[tail] = m;
        // 循环队列 tail=7 8越界了,(7+1)%8==0
        tail = (tail + 1) % n;
    }
    public int pop(){
        if(isEmpty()){
            return -1;
        }
        int m = data[head];
        head = (head + 1) % n;
        return m;
    }
    public boolean isEmpty(){
        return head == tail;
    }

    public static void main(String[] args) {
        CircleArrayQueue arrayQueue = new CircleArrayQueue(6);
        arrayQueue.push(1);
        arrayQueue.push(2);
        arrayQueue.push(3);
        arrayQueue.push(4);
        arrayQueue.push(5);
        int[] date = arrayQueue.data;
        System.out.println(date.length);
        for (int i : date) {
            System.out.println(i);
            int pop = arrayQueue.pop();
            System.out.println("弹出来的是: "+ pop);
        }
    }
}

记录学习历程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值