数据结构——队列

167 阅读1分钟

队列

JS中可以用数组模拟队列

  • 特点:先进先出
const queue = []
queue.push(1)
queue.push(2)
const item1 = queue.shift()
const item2 = queue.shift()

使用队列的场景

  1. 食堂排队打饭
  2. JS异步中的任务队列
  3. 计算最近请求次数

933: leetcode-cn.com/problems/nu…

image.png

var RecentCounter = function() {
    this.queue = [];

};

RecentCounter.prototype.ping = function(t) {
    this.queue.push(t)
    while (this.queue[0] <  t-3000){
        this.queue.shift()
    }
    return this.queue.length
};

JS中可以用数组模拟栈

  • 特点:后进先出
const stack = []
stack.push(1)
stack.push(2)
const item2 = stack.pop()
const itme1 = stack.pop()

使用队列的场景

  1. 十进制转二进制
  2. 判断字符串中的括号是否有效匹配
  3. 函数调用堆栈

链表

链表是由多个元素组成的列表,元素存储不连续,用next指针连接

链表和数组的对比

数组: 增删非首位元素时往往需要移动元素

JS中没有链表,我们用对象模拟链表

const a = {val: 'a'}
const b = {val: 'b'}
const c = {val: 'c'}
const d = {val: 'd'}
a.next = b;
b.next = c;
d.next = d

遍历链表

let p = a;
while(p){
  console.log(p.val)
  p = p.next
}

插入

const e = {val : 'e'}
c.next = e
e.next = d 

删除

//删除e
c.next = d 

leetcode题目

删除链表中的节点

  • 解题思路
  1. 无法直接获取被删除节点的上个节点
  2. 将被删除节点转移到下个节点
  • 解题步骤 1.将被删除节点的值改为下个节点的值 2.删除下个节点