队列复习

导语

队列是一种受限的线性表数据结构,它只允许前端进行删除操作,后端进行插入操作。队列中特殊的有循环队列、阻塞队列、并发队列。

队列分类

由数组组成的成为顺序队列,由链表实现的是链式队列。

顺序队列

public class ArrayQueue {
    //定义一个数组items,大小n
    private String[] items;
    private int n = 0;

    public ArrayQueue(int capacity) {
        items = new String[capacity];
        n = capacity;
    }

    //定义队头下标和队尾下标
    private int head = 0;
    private int tail = 0;


    //入队
    public boolean enqueue(String item) {
        if (tail != n) {
            items[tail] = item;
            tail++;
            return true;
        } else {
            if (head == 0) return false;
            for (int i = head; i < n; i++) {
                items[i - head] = items[i];
            }
            tail -= head;
            head = 0;
            items[tail] = item;
            tail++;
            return true;
        }
    }

    //出队
    public String dequeue() {
        if (tail == head) return null;
        String item = items[head];
        head++;
        return item;
    }
}

如果头标记和尾标都在右移,可能出现tail==n,head == tail-1 ,head 前边的数据空间都不能被利用的情况,这里入列时要考虑数据搬移。

链式队列

public class LinkQueue {
    private LinkNode head;

    public LinkQueue() {
    }

    //入列
    public void enqueue(int data) {
        LinkNode newHead = new LinkNode(data);
        if (head == null) {
            head = newHead;
        }
        head.next = newHead;
    }

    //出列
    public int dequeue() {
        if (head == null) return 0;
        int data = head.data;
        head = head.next;
        return data;
    }
}

循环队列

循环队列可以有效解决数据搬移问题
循环队列
循环队列队满情况

public class CircularQueue {
    private String[] items;
    private int head;
    private int tail;
    private int n;

    public CircularQueue(int capacity) {
        items = new String[capacity];
        n = capacity;
    }

    public String dequeue() {
        if (head == tail) return null;
        String item = items[head];
        head++;
        return item;
    }

    //队满时的规律是 (tail + 1) % n == head
    public boolean enqueue(String item) {
        if ((tail + 1) % n == head) return false;
        items[tail] = item;
        tail = (tail + 1) % n;
        return true;
    }
}

阻塞队列&并发队列

类似于生产者和消费者模式,我们可以使用阻塞队列来实现。比如BlockingQueue
生产者消费者阻塞队列实现

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值