-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathstack.js
More file actions
67 lines (58 loc) · 1.2 KB
/
Copy pathstack.js
File metadata and controls
67 lines (58 loc) · 1.2 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Stack {
constructor() {
this.count = 0
this.items = {}
}
/** 入栈 */
push(element) {
this.items[this.count] = element;
this.count++
}
/** 出栈 */
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]
}
/** 栈是否为空 */
isEmpty() {
return this.count === 0
}
/** 清空栈 */
clear() {
this.count = 0
this.items = {}
// 或则遵守LIFO原则
// while (!this.isEmpty()) {
// this.pop()
// }
}
/** 栈长 */
size() {
return this.count
}
/** 拓展-输出当前栈 */
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;
}
}
module.exports = Stack
// test
// const xxx = new Stack()
// xxx.push(3)
// xxx.push(2)
// console.log('pop = ', xxx.pop());
// console.log('peek = ', xxx.peek());
// console.log('toString = ', xxx.toString());