『数据结构与算法』—— 队列

定义

有一定的业务需求就会有对应的技术或数据结构产生。我们都知道 CPU 的资源是有限的,任务的处理速度与线程个数并不是线性正相关。相反过多的线程反而会导致 CPU 频繁切换,处理性能下降。所以线程池的大小一般都是综合考虑处理任务的特点和硬件环境,来事先设置的。

队列的特点 先进先出,可以想象成排队买票,先来的先买。最基本的操作就是 入队和出队,所以队列跟栈一样,也是一种 操作受限的线性数据结构

实现

类似栈,可以通过数组和链表试下,数组实现的队列叫做 顺序队列,链表实现的队列叫做 链式队列

顺序队列

核心思想在于,使用两个下标保存头部和尾部的数据,也可以当成标识。因为入队是从屁股进行插入,出队是从头部拿出数据,因此要记住头尾的位置。

先来看一下简单的实现方式:

class ArrayQueue<T> {
    T[] items;
    int head;
    int tail;
    int count;

    ArrayQueue(int capacity) {
        items = (T[]) new Object[capacity];
        count = capacity;
    }

    boolean enqueue(T t) {
        if (tail == count) return false;
        items[tail] = t;
        tail ++;
        print("enqueue");
        return true;
    }

    T dequeue() {
        if (head == tail) return null;
        T t= items[head];
        items[head] = null;
        head ++;
        print("dequeue");
        return t;
    }

    void print(String mode) {
        System.out.println("mode:\t" + mode + " head:\t" + head + " tail:\t" + tail);
        for (int i = head; i < tail; i++) {
            System.out.print(items[i] + "");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        ArrayQueue<String> queue = new ArrayQueue<String>(6);
        queue.enqueue("1");
        queue.enqueue("2");
        queue.enqueue("3");
        queue.dequeue();
        queue.dequeue();
        queue.dequeue();
        queue.enqueue("5");
        queue.enqueue("6");
    }
}

运行结果:

mode:   enqueue head:   0 tail: 1
1
mode:   enqueue head:   0 tail: 2
12
mode:   enqueue head:   0 tail: 3
123
mode:   dequeue head:   1 tail: 3
23
mode:   dequeue head:   2 tail: 3
3
mode:   dequeue head:   3 tail: 3

mode:   enqueue head:   3 tail: 4
5
mode:   enqueue head:   3 tail: 5
56

上述实现的方式有一个弊端,当 tail == n 的时候,就不能继续插入数据,但是此时容器并没有装满,只是不能继续往后插入数据了。那这个时候就需要对容器进行改变:数据搬移。单并不是每次入队都需要迁移,为了优化时间复杂度,可以在每次尾节点到达终点时,再开始数据搬移,即数据往前移动 head 的位置。

来看一下实现方式:

class DynamicArrayQueue<T> {
    T[] items;
    int head;
    int tail;
    int count;

    DynamicArrayQueue(int capacity) {
        items = (T[]) new Object[capacity];
        count = capacity;
    }

    boolean enqueue(T t) {
        if (tail == count) {
            if (head == 0) return false;
            for (int i = head; i < tail; i++) {
                items[i - head] = items[i];
            }
            tail -= head;
            head = 0;
        }
        items[tail] = t;
        tail ++;
        print("enqueue");
        return true;
    }

    T dequeue() {
        if (head == tail) return null;
        T t = items[head];
        items[head] = null;
        head ++;
        print("new dequeue");
        return t;
    }

    void print(String mode) {
        System.out.println("mode:\t" + mode + " head:\t" + head + " tail:\t" + tail);
        for (int i = head; i < tail; i++) {
            System.out.print(items[i] + "");
        }
        System.out.println();
        System.out.println(Arrays.toString(items));
    }

    public static void main(String[] args) {
        DynamicArrayQueue<String> queue = new DynamicArrayQueue<String>(4);
        queue.enqueue("1");
        queue.enqueue("2");
        queue.enqueue("3");
        queue.enqueue("4");
        queue.dequeue();
        queue.dequeue();
        queue.enqueue("5");
        queue.enqueue("6");
    }
}

结果:

mode:   enqueue head:   0 tail: 1
1
[1, null, null, null]
mode:   enqueue head:   0 tail: 2
12
[1, 2, null, null]
mode:   enqueue head:   0 tail: 3
123
[1, 2, 3, null]
mode:   enqueue head:   0 tail: 4
1234
[1, 2, 3, 4]
mode:   new dequeue head:   1 tail: 4
234
[null, 2, 3, 4]
mode:   new dequeue head:   2 tail: 4
34
[null, null, 3, 4]
mode:   enqueue head:   0 tail: 3
345
[3, 4, 5, 4]
mode:   enqueue head:   0 tail: 4
3456
[3, 4, 5, 6]
mode:   new dequeue head:   1 tail: 4
456
[null, 4, 5, 6]
mode:   enqueue head:   0 tail: 4
4567
[4, 5, 6, 7]

想比较之前的实现,出队的逻辑并没有任何的改变,在入队是,需要判断 tail == 0,如果达到这个条件则可能需要进行数据搬移。

链式队列

思路其实类似于顺序队列的实现逻辑。

class LinkedQueue<T> {
    Node<T> head = null;
    Node<T> tail = null;

    void enqueue(T t) {
        if (tail == null) {
            Node<T> node = new Node<T>(t, null);
            head = node;
            tail = node;
        } else {
            tail.next = new Node<T>(t, null);
            tail = tail.next;
        }
        System.out.println(head.toString());
    }

    T dequeue() {
        if (head == null) return null;
        T t = head.value;
        head = head.next;
        if (head == null) {
            tail = null;
        }
        System.out.println(head == null ? "null" : head.toString());
        return t;
    }

    public static void main(String[] args) {
        LinkedQueue<String> queue = new LinkedQueue<String>();
        queue.enqueue("1");
        queue.enqueue("2");
        queue.enqueue("3");
        queue.dequeue();
        queue.dequeue();
        queue.enqueue("6");
    }
}

运行结果:

1 
1 2 
1 2 3 
2 3 
3 
3 6 

需要注意的是:

  1. 入队的时候,需要考虑队列无数据的情况
  2. 出队的时候,需要考虑出队到最后尾节点的处理

循环队列

之前在用数组实现队列时,在 tail == n 时会有数据搬移的操作,这样入队操作性能就会收到影响,我们可以使用循环队列来解决这个问题。

循环队列其实长得像一个环,现在需要将首尾相连变成一个环。

放三张图感受一下,图片来自于极客时间的课程。

image
image
image

从图中可以发现规律,当 (tail + 1) % n = head 时,说明队列已满。

来看一下代码的具体实现方式:

class CircularQueue {
    // 数组:items,数组大小:n
    private String[] items;
    private int n = 0;
    // head表示队头下标,tail表示队尾下标
    private int head = 0;
    private int tail = 0;

    // 申请一个大小为capacity的数组
    public CircularQueue(int capacity) {
        items = new String[capacity + 1];
        n = capacity + 1;
    }

    // 入队
    public boolean enqueue(String item) {
        // 队列满了
        if ((tail + 1) % n == head) return false;
        items[tail] = item;
        tail = (tail + 1) % n;
        return true;
    }

    // 出队
    public String dequeue() {
        // 如果head == tail 表示队列为空
        if (head == tail) return null;
        String ret = items[head];
        head = (head + 1) % n;
        return ret;
    }

    public void printAll() {
        if (0 == n) return;
        for (int i = head; i % n != tail; ++i) {
            System.out.print(items[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        CircularQueue queue = new CircularQueue(5);
        queue.enqueue("1");
        queue.enqueue("2");
        queue.enqueue("3");
        queue.enqueue("4");
        queue.printAll();
        queue.dequeue();
        queue.printAll();
        queue.enqueue("5");
        queue.enqueue("6");
        queue.printAll();
    }
}

运行结果:

1 2 3 4 
2 3 4 
2 3 4 5 6 

参考自极客时间

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容