In this lesson, you will learn how to create a queue in JavaScript. A queue is a first-in, first-out data structure (FIFO). We can only remove items from the queue one at a time, and must remove items in the same sequence as they were placed in the queue.

Also learn how we can combine several queues to create a new data structure: a priority queue. A priority queue allows the user to add items to the queue that are deemed to be high priority, and get moved ahead in the line. This added complexity is simple to achieve and is a good example of how we can build up complexity through the use of data structures.

/**
*
* Queue
*
* First in First out
*
* API:
*
* enqueue() - Push a new item to the first place
* dequeue() - Get first in item from the last of array
* peek() - Check the next item in the queue
* length
* isEmpty()
*/ function createQueue() {
const queue = [];
return {
enqueue(item) {
queue.unshift(item);
},
dequeue() {
return queue.pop();
},
peek() {
return queue[queue.length - 1];
},
get length() {
return queue.length;
},
isEmpty() {
return queue.length === 0;
},
};
} /**
*
* Priority Queue
*
* First in First out for priority list and normal list
*
* API:
*
* enqueue() - Push a new item to the first place
* dequeue() - Get first in item from the last of array
* peek() - Check the next item in the queue
* length
* isEmpty()
*/
function createPriorityQueue() {
const queue = createQueue();
const p_queue = createQueue();
return {
enqueue (item, isPriority) {
if (isPriority) {
return p_queue.enqueue(item)
} queue.enqueue(item)
},
dequeue () {
if (!p_queue.isEmpty()) {
return p_queue.dequeue()
} return queue.dequeue()
},
peek () {
if (!p_queue.isEmpty()) {
return p_queue.peek()
} return queue.peek()
},
get length () {
return p_queue.length + queue.length;
},
isEmpty () {
return p_queue.isEmpty() && queue.isEmpty();
}
}
} module.exports = {createQueue, createPriorityQueue}; const q = createQueue();
q.enqueue("Learn algorithoms");
q.enqueue("Learn data structure");
q.enqueue("Learn thinking"); console.log(q.peek()); // 'Learn algorithoms'
q.dequeue();
console.log(q.peek()); // 'Learn data structure'
q.dequeue();
console.log(q.peek()); // 'Learn thinking'
q.dequeue();
console.log(q.isEmpty()); const pq = createPriorityQueue()
pq.enqueue('A fix here')
pq.enqueue('A bug there')
pq.enqueue('A new feature') pq.dequeue()
pq.enqueue('Emergency task!', true)
console.log(pq.dequeue())
console.log(pq.peek())

Notice 'unshift' function time Complixty is not O(1). For Queue, better have enqueue and dequeue both O(1): to achieve that we can use Map:

function Queue() {
let data = new Map();
let lastDeQueueIndex = ;
let nextEnQueueIndex = ;
return {
enqueue(item) {
// O(1)
data.set(nextEnQueueIndex, item);
nextEnQueueIndex++;
},
dequeue() {
// O(1)
const item = data.get(lastDeQueueIndex);
lastDeQueueIndex++;
return item;
},
size() {
return nextEnQueueIndex - lastDeQueueIndex;
}
};
}
 
 

[Algorithms] Queue & Priority Queue的更多相关文章

  1. [置顶] ※数据结构※→☆线性表结构(queue)☆============优先队列 链式存储结构(queue priority list)(十二)

    优先队列(priority queue) 普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除.在优先队列中,元素被赋予优先级.当访问元素时,具有最高优先级的元素最先删除.优先队列具有 ...

  2. 《Algorithms 4th Edition》读书笔记——2.4 优先队列(priority queue)-Ⅴ

    命题Q.对于一个含有N个元素的基于堆叠优先队列,插入元素操作只需要不超过(lgN + 1)次比较,删除最大元素的操作需要不超过2lgN次比较. 证明.由命题P可知,两种操作都需要在根节点和堆底之间移动 ...

  3. Algorithms - Priority Queue - 优先队列

    Priority queue - 优先队列 相关概念 Priority queue优先队列是一种用来维护由一组元素构成的集合S的数据结构, 其中的每一种元素都有一个相关的值,称为关键字(key). 一 ...

  4. 《Algorithms 4th Edition》读书笔记——2.4 优先队列(priority queue)-Ⅳ

    2.4.4 堆的算法 我们用长度为 N + 1的私有数组pq[]来表示一个大小为N的堆,我们不会使用pq[0],堆元素放在pq[1]至pq[N]中.在排序算法中,我们只能通过私有辅助函数less()和 ...

  5. 《Algorithms 4th Edition》读书笔记——2.4 优先队列(priority queue)-Ⅰ

    许多应用程序都需要处理有序的元素,但不一定要求他们全部有序,或者是不一定要以此就将他们排序.很多情况下我们会手机一些元素,处理当前键值最大的元素,然后再收集更多的元素,再处理当前键值最大的元素.如此这 ...

  6. Priority Queue

    优先队列 集合性质的数据类型离不开插入删除这两操作,主要区别就在于删除的时候删哪个,像栈删最晚插入的,队列删最早插入的,随机队列就随便删,而优先队列删除当前集合里最大(或最小)的元素.优先队列有很多应 ...

  7. STL-<queue>-priority queue的使用

    简介: 优先队列是一种容器适配器,优先队列的第一个元素总是最大或最小的(自定义的数据类型需要重载运算符).它是以堆为基础实现的一种数据结构. 成员函数(Member functions) (const ...

  8. 优先队列(Priority Queue)

    优先队列(Priority Queue) A priority queue must at least support the following operations: insert_with_pr ...

  9. Objective-C priority queue

    http://stackoverflow.com/questions/17684170/objective-c-priority-queue PriorityQueue.h // // Priorit ...

随机推荐

  1. 理解依赖注入 for Zend framework 2

    依赖注入(Dependency Injection),也成为控制反转(Inversion of Control),一种设计模式,其目的是解除类之间的依赖关系. 假设我们需要举办一个Party,Part ...

  2. ptyhon - 接口自动化测试实战case1

    work_20181203_httprequest.py: import requestsclass http_request: def http_get(url,params): res = req ...

  3. 聊聊、Jstack 解决生产问题

    最近项目很多,所在公司是一家金融企业.从 APP 端到 基金公司,整个体系涉及到很多系统.而我所负责的,正好是整个体系尾部,业务核心.前段时间,隔几天总会有用户购买理财产品失败,但是日志里面没有任何异 ...

  4. 【mysql 优化 4】嵌套连接优化

    原文地址:Nested Join Optimization 与SQL标准相比,table_factor的语法被扩展.后者仅接受table_reference,而不是一对括号内的列表.如果我们将tabl ...

  5. Welcome-to-Swift-01基础部分

    Swift 是 iOS 和 OS X 应用开发的一门新语言.然而,如果你有 C 或者 Objective-C 开发经验的话,你会发现 Swift 的很多内容都是你熟悉的. Swift 的类型是在 C ...

  6. 安装环境 :win64

    1.安装环境 :win64 1.1 下载mysql安装包地址: https://dev.mysql.com/downloads/file/?id=476233 2.安装 2.1 解压下载的ZIP压缩包 ...

  7. Gcd(bzoj 2818)

    Description 给定整数N,求1<=x,y<=N且Gcd(x,y)为素数的数对(x,y)有多少对. Input 一个整数N Output 如题 Sample Input 4 Sam ...

  8. vue.js源码学习分享(八)

    /* */ var uid$1 = 0; /** * A dep is an observable that can have multiple * directives subscribing() ...

  9. 转 Perl函数返回值用法指导

    http://developer.51cto.com/art/201007/213003.htm Perl函数返回值用法指导   Perl编程语言中Perl函数返回值用法你是否比较熟悉,这里向大家简单 ...

  10. java 四种方式实现字符流文件的拷贝对比

    将D:\\应用软件\\vm.exe  拷贝到C:\\vm.exe   四种方法耗费时间对比  4>2>3>1 package Copy; import java.io.Buffere ...