栈、链表模拟队列

数组vs链表:

二者都是有序结构,都是物理结构。栈是逻辑结构,抽象模型
链表:查询慢O(n),新增和删除快O(1)
数组:查询快O(1),新增和删除慢O(n)

1、栈模拟队列 。时间复杂度O(n),空间复杂度O(n)。

数组是连续存储结构,删除时使用shift()出队,后面的每个元素都要变动,时间复杂度O(n)。

class MyQueue {
    constructor() {
        this.stack1 = []
        this.stack2 = []
    }
    add(n) {
        this.stack1.push(n)
    }

    delete() {
        let res
        while (this.stack1.length) {
            const n = this.stack1.pop()
            if (n != null) {
                this.stack2.push(n)
            }
        }
        res = this.stack2.pop()
        while (this.stack2.length) {
            const n = this.stack2.pop()
            if (n != null) {
                this.stack1.push(n)
            }
        }
        return res || null
    }

    get length() {
        return this.stack1.length
    }
}

2、链表模拟队列。时间复杂度O(1),空间复杂度O(n)

function ListNode(val = undefined, n = null) {
    this.val = val
    this.next = n
}
class MyQueue {
    constructor() {
        this.head = null
        this.tail = null
        this.len = 0
    }
    add(n) {
        const newNode = new ListNode(n)
        //处理head
        if (this.head == null) {
            this.head = newNode
        }
        //处理tail
        const tailNode = this.tail
        if (tailNode) {
            tailNode.next = newNode
        }
        this.tail = newNode
        this.len++
    }

    delete() {
        if (this.head == null || this.len <= 0) return null
        const headNode = this.head
        const val = headNode.val
        this.head = headNode.next
        this.len--
        return val
    }
    //length单独存储,不能遍历链表获取,否则时间复杂度过高,为O(n)
    get length() {
        return this.len
    }
}

//测试代码
const q = new MyQueue()
q.add(100)
q.add(200)
q.add(300)
console.log(q.length);
q.delete()
console.log(q.length); 

因此,用链表实现,性能更好(前端重时间,轻空间)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值