-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.js
More file actions
48 lines (37 loc) · 747 Bytes
/
stack.js
File metadata and controls
48 lines (37 loc) · 747 Bytes
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
class Stack {
constructor() {
this.data = [];
this.top = 0;
}
// 元素进栈的
push(element) {
this.data[this.top++] = element;
}
// 获得栈顶元素
peek(element) {
if (!this.top) throw new Error('栈里面没有元素');
return this.data[this.top - 1];
}
//弹出栈顶元素
pop() {
if (!this.top) throw new Error('栈里面没有元素');
return this.data[--this.top];
}
// 清空栈
clear() {
this.top = 0;
}
// 获取栈的深度
length() {
return this.top;
}
};
// e.g
// const stack = new Stack ()
// stack.push(1)
// stack.push(2)
// stack.push(3)
// stack.push(4)
// console.log(stack.pop())
// console.log(stack.length())
// console.log(stack.peek())