【九月打卡】第20天 算法(3)
標(biāo)簽:
JavaScript
课程名称:2周刷完100道前端优质面试真题
课程章节:第2章 前端面试技能拼图1 :数据结构和算法(上),大厂面试必考
主讲老师:双越
课程内容:
今天学习的内容包括:
2-12 【连环问】链表和数组哪个实现队列更快-分析解题思路
2-13 【连环问】链表和数组哪个实现队列更快-代码演示和单元测试
2-14 【连环问】链表和数组哪个实现队列更快-性能分析
这几节主要是讲怎么用链表实现队列。
课程收获:
主要内容大致复述如下。
-
链表实现队列
设置私有属性两个指针分别指向链表头和尾。
入队从链表尾入链表,注意表头表尾为空的情况。当前队尾的 next 指向新节点,尾指针指向新节点。
出队从链表头删除,依然是要注意表头为空的情况。当只有一个节点时,尾节点记得处理。出队返回当前表头值,头指针指向当前节点的下一个节点。
class queue {
constructor() {
this.head = null;
this.tail = null;
}
// tail 添加
append(val) {
const node = {
val,
next: null,
};
if (this.head == null) {
this.head = node;
}
if (this.tail) {
this.tail.next = node;
}
this.tail = node;
}
// head 删除 返回删除节点值
delete() {
if (this.head == null) {
return null;
}
let headVal = this.head.val;
if (this.head.next == null) {
this.tail = null;
}
this.head = this.head.next;
return headVal;
}
}
const q = new queue();
q.append(100);
console.info("queue1", q.head, q.tail);
q.delete();
console.info("queue2", q.head, q.tail);
q.append(200);
q.append(300);
q.append(400);
console.info("queue3", q.head, q.tail);
-
链表 or 数组实现队列的比较
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫(xiě)下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦