JS用链表实现队列,附测试代码
Posted hans774882968
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS用链表实现队列,附测试代码相关的知识,希望对你有一定的参考价值。
我偶然查了查网上js实现队列、优先队列的代码,tmd全是直接封装数组,学前端的难道没一个会算法的?
在此提供一份队列的实现,使用链表。附测试数据,以及NC114的AC代码(注:这份代码居然跑得比用js数组做队列的要慢555)。
实现
class ListNode {
constructor(v = -1, n = null) {
this.val = v
this.next = n
}
}
class Queue {
constructor() {
let u = new ListNode()
this.hd = u
this.tl = u
this.sz = 0
}
push(v) {
let u = new ListNode(v)
this.tl.next = u
this.tl = u
this.sz++
}
pop() {
if (!this.sz) return
this.hd = this.hd.next
this.sz--
}
front() {
if (!this.sz) return
return this.hd.next.val
}
size() {
return this.sz
}
empty() {
return this.sz <= 0
}
}
测试
let q = new Queue()
console.log(q.front(),q.size(),q.empty())//undefined 0 t
q.push(10)
console.log(q.front(),q.size(),q.empty())//10 1 f
q.push('wsw')
console.log(q.front(),q.size(),q.empty())//10 2 f
q.pop()
console.log(q.front(),q.size(),q.empty())//'wsw' 1 f
q.pop()
console.log(q.front(),q.size(),q.empty())//undefined 0 t
q.pop()
console.log(q.front(),q.size(),q.empty())//undefined 0 t
q.push(18)
console.log(q.front(),q.size(),q.empty())//18 1 f
for (let i = 19; i < 30; ++i) q.push(i)
for (let i = 19; i <= 31; ++i) {
q.pop()
console.log(q.front(), q.size(), q.empty())//19~29及两个undefined
}
q.push(114514)
console.log(q.front(), q.size(), q.empty())//114514 1 f
NC114
"use strict";
class ListNode {
constructor(v = -1, n = null) {
this.val = v
this.next = n
}
}
class Queue {
constructor() {
let u = new ListNode()
this.hd = u
this.tl = u
this.sz = 0
}
push(v) {
let u = new ListNode(v)
this.tl.next = u
this.tl = u
this.sz++
}
pop() {
if (!this.sz) return
this.hd = this.hd.next
this.sz--
}
front() {
if (!this.sz) return
return this.hd.next.val
}
size() {
return this.sz
}
empty() {
return this.sz <= 0
}
}
function Print(pRoot) {
// write code here
let q = new Queue()
if (pRoot) q.push(pRoot)
let ans = []
for (let dis = 0; !q.empty(); ++dis) {
let sz = q.size()
let cur = []
while (sz--) {
const u = q.front()
q.pop()
cur.push(u.val)
if (u.left) q.push(u.left)
if (u.right) q.push(u.right)
}
ans.push(dis % 2 ? cur.reverse() : cur)
}
return ans
}
module.exports = {
Print : Print
};
以上是关于JS用链表实现队列,附测试代码的主要内容,如果未能解决你的问题,请参考以下文章