栈是一种遵从后进先出(LIFO)原则的有序集合。新添加或待删除的元素都保存在栈的同一端,称作栈顶,另一端就叫栈底。在栈里,新元素都靠近栈顶,旧元素都接近栈底。

创建一个基于数组的Stack类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Stack {
// 构造函数
constructor() {
this.items = [];
}
// 向栈添加元素
push(element) {
this.items.push(element);
}
// 从栈移除元素
pop() {
return this.items.pop();
}
// 查看栈顶元素
peek() {
return this.items[this.items.length - 1];
}
// 检查栈是否为空
isEmpty() {
return this.items.length === 0;
}
// 获取栈的大小
size() {
return this.items.length;
}
// 清空栈元素
clear() {
this.items = [];
}
}

创建一个基于JavaScript对象的Stack类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Stack {
// 构造函数
constructor() {
this.count = 0;
this.items = {};
}
// 向栈中插入元素
push(element) {
this.items[this.count] = element;
this.count++;
}
// 获取栈的大小
size() {
return this.count;
}
// 检查栈是否为空
isEmpty() {
return this.count == 0;
}
// 从栈中弹出元素
pop() {
if (this.isEmpty()) {
return undefined;
}
this.count--;
const result = this.items[this.count];
delete this.items[this.count];
return result;
}
// 查看栈顶元素
peek() {
if (this.isEmpty()) {
return undefined;
}
return this.items[this.count - 1];
}
// 清空栈元素
clear() {
this.items = {};
this.count = 0;
}
// 创建toString方法
toString() {
if (this.isEmpty()) {
return "";
}
let objString = `${this.items[0]}`;
for (let i = 1; i < this.count; i++) {
objString = `${objString}, ${this.items[i]}`;
}
return objString;
}
}

这里就不再演示Stack类中方法的使用了,有兴趣的可以自己做个demo测试一下,如果有任何的问题,欢迎评论区留言。

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020-2021 Sanmu
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信