1.栈结构 Stack:
特点:
- 后进先出 LIFO (last in first out)
- 只能在一端操作(顶端 front):包括增加(进栈)和删除(出栈)
- 递归算法中的无限递归会出现栈溢出
代码实现:
class Stack {
container = [];
enter(element) {
this.container.unshift(element);
}
leave() {
return this.container.shift();
}
size() {
return this.container.length;
}
value() {
return this.container.slice(0);
}
}
常见面试题(场景运用)—十进制转为二进制:
Number.prototype.decimal2binary = function decimal2binary() {
let sk = new Stack,
decimalNum = this.valueOf();
if (decimalNum === 0) return '0';
while (decimalNum > 0) {
sk.enter(decimalNum % 2);
decimalNum = Math.floor(decimalNum / 2);
}
return sk.value().join('');
};
console.log((10).decimal2binary());
2.队列结构 Queue:
特点:
- 先进先出 FIFO (First In First Out) 允许在前端(front)删除
- 允许在后端(rear)插入
- 特殊:优先级队列
代码实现:
class Queue {
container = [];
enter(element) {
this.container.push(element);
}
leave() {
return this.container.shift();
}
size() {
return this.container.length;
}
value() {
return this.container.slice(0);
}
}
常见面试题(场景运用)—击鼓传花:
function game(n, m) {
let qe = new Queue;
for (let i = 0; i < n; i++) {
qe.enter(i + 1);
}
while (qe.size() > 1) {
for (let i = 0; i < m - 1; i++) {
qe.enter(qe.leave());
}
qe.leave();
}
return qe.value().toString();
}
console.log(game(8, 5));
|