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. Python 前端 js基础

    Javascript 概述 JavaScript是一门编程语言,浏览器内置了JavaScript语言的解释器,所以在浏览器上按照JavaScript语言的规则编写相应代码之,浏览器可以解释并做出相应的 ...

  2. 30、自定义gridview

    要想实现自定义gridview效果,有下边几个步骤: 1.定义grivew中的item的xml文件 假如item需要显示一个图片,图片下边显示文字: <?xml version="1. ...

  3. 聊聊、Highcharts 动态数据优化版

    好久没来博客园了,最近项目太紧.上一篇写了 <Highcharts 之[动态数据]>,不够完善,虽然横纵轴可以动态取数据,但是行业信息是固定的,不能随着大数据热点改变.废话不说,直接上代码 ...

  4. [uiautomator篇][exist 存在,但click错误]

    uiautomator定位页面元素是,定位存在的;但是click的时候,发现点的位置不对,(不知道是android系统的问题还是uiautomator的问题,初步怀疑是系统的问题)

  5. C语言总结(5)

    一.函数的定义: 函数是一个完成特定工作的独立程序模块,包括库函数和自定义函数.例如:scanf(),printf()为库函数,cylinder(),fact()为自定义函数. 函数定义的一般形式: ...

  6. Python之自动单元测试之一(unittest使用实例)

    软件的测试是一件非常乏味的事情,在测试别人编写的软件时尤其如此,程序员通常都只对编写代码感兴趣,而不喜欢文档编写和软件测试这类"没有创新"的工作.既然如此,为什么不让程序员在编写软 ...

  7. java maven项目testng执行时使用的是test-classes下的文件,共享main下方resource的配置

    在pom.xml中配置 <build> <testResources> <testResource> <directory>${project.base ...

  8. Python ping 模块

    使用socket模块也可以获得域名对应的ip,参考:https://blog.csdn.net/c465869935/article/details/50850598 print socket.get ...

  9. spoj 7001 Visible Lattice Points莫比乌斯反演

    Visible Lattice Points Time Limit:7000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu Su ...

  10. OSU!(bzoj 4318)

    Description osu 是一款群众喜闻乐见的休闲软件.  我们可以把osu的规则简化与改编成以下的样子:  一共有n次操作,每次操作只有成功与失败之分,成功对应1,失败对应0,n次操作对应为1 ...