【数据结构】手写队列

114 阅读1分钟

目标:

使用js实现一个队列结构。

队列特点

  • 先进先出;
  • 一端插入一端删除;

队列属性、方法

方法:enqueue、dequeue、count、getFirst、includes...

image.png

队列类型

顺序队列、链式队列

顺序队列

用数组可以实现顺序队列

class Queue {
    constructor() {
        this.items = [];
    }
    enqueue(element) {
        this.items.push(element);
    }
    dequeue() {
        if (this.isEmpty()) {
            return null;
        }
        return this.items.shift();
    }
    getFirst() {
        if (this.isEmpty()) {
            return null;
        }
        return this.items[0];
    }
    isEmpty() {
        return this.items.length === 0;
    }
    count() {
        return this.items.length;
    }
    clear() {
        this.items = [];
    }
}

链式队列

链式队列和单向循环链表实现很相似,不同点是链式队列只能尾部添加元素,队首删除元素。

class Node {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

  
class Queue {
    constructor() {
        this.head = null;
        this.tail = null;
        this.size = 0;
    }

    enqueue(value) {
        const newNode = new Node(value);
        if (this.isEmpty()) {
            this.head = newNode;
            this.tail = newNode;
        } else {
            this.tail.next = newNode;
            this.tail = newNode;
        }
        this.size++;
    }

    dequeue() {
        if (this.isEmpty()) return null;
        const removedNode = this.head;
        this.head = this.head.next;
        if (this.head === null) {
            this.tail = null;
        }
        this.size--;
        return removedNode.value;
    }

    getFirst() {
        if (this.isEmpty()) return null;
        return this.head.value;
    }

    isEmpty() {
        return this.size === 0;
    }

    count() {
        return this.size;
    }

    clear() {
        this.head = null;
        this.tail = null;
        this.size = 0;
    }

}