随笔- 100  文章- 0  评论- 3  阅读- 30413 

  特殊的线性表,插入在队尾,删除的是对头。

  先进先出。

 

一:队列

1.普通队列实现

复制代码
package com.jun.algorithm.foundation.main;

/**
 * 使用数组实现队列
 *
 * @author caojun
 */
public class ArrayQueue {

    private int[] data;
    // 对头的位置
    private int head = 0;
    // 队尾的位置
    private int tail = 0;
    // 队列长度
    private int n = 0;

    ArrayQueue(int cap) {
        data = new int[cap];
        n = cap;
    }

    public void push(int num) {
        // 如果没有空间了,移动一次
        if (tail == n) {
            return;
        }
        data[tail] = num;
        tail++;
    }

    public int pop() {
        if (isEmpty()) {
            return -1;
        }
        int m = data[head];
        head++;
        return m;
    }

    public boolean isEmpty() {
        return head == tail;
    }


}
复制代码

 

2.循环队列实现

复制代码
package com.jun.algorithm.foundation.main;

/**
 * 使用数组实现循环队列
 *
 * @author caojun
 */
public class CircleArrayQueue {

    private int[] data;
    // 对头的位置
    private int head = 0;
    // 队尾的位置
    private int tail = 0;
    // 队列长度
    private int n = 0;

    CircleArrayQueue(int cap) {
        data = new int[cap];
        n = cap;
    }

    public void push(int num) {
        // 满了的判断条件
        if ((tail + 1) % n == head) {
            return;
        }
        data[tail] = num;
        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;
    }


}
复制代码

 

 posted on   曹军  阅读(45)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示