[Algorithms] Queue & Priority Queue

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 = 0;
  let nextEnQueueIndex = 0;
  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;
    }
  };
}
复制代码

 

 

 
 
posted @   Zhentiw  阅读(194)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-12-12 [Python] Reuse Code in Multiple Projects with Python Modules
2016-12-12 [D3] Load and Inspect Data with D3 v4
2016-12-12 [Now] Update an application hosted with Zeit’s Now
2016-12-12 [JS Compose] 1. Refactor imperative code to a single composed expression using Box
2014-12-12 [MongoDB] Insert, find -- 1
点击右上角即可分享
微信分享提示