forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackBasedOnLinkedList.js
More file actions
62 lines (59 loc) · 1.2 KB
/
StackBasedOnLinkedList.js
File metadata and controls
62 lines (59 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
/**
* 基于链表实现的栈。
*
* Author: nameczz
*/
class Node {
constructor(element) {
this.element = element
this.next = null
}
}
class StackBasedLinkedList {
constructor() {
this.top = null
}
push(value) {
const node = new Node(value)
if (this.top === null) {
this.top = node
} else {
node.next = this.top
this.top = node
}
}
pop() {
if (this.top === null) {
return -1
}
const value = this.top.element
this.top = this.top.next
return value
}
// 为了实现浏览器前进后退
clear() {
this.top = null
}
display() {
if (this.top !== null) {
let temp = this.top
while (temp !== null) {
console.log(temp.element)
temp = temp.next
}
}
}
}
// Test
const newStack = new StackBasedLinkedList()
newStack.push(1)
newStack.push(2)
newStack.push(3)
// 获取元素
let res = 0
console.log('-------获取pop元素------')
while (res !== -1) {
res = newStack.pop()
console.log(res)
}
exports.CreatedStack = StackBasedLinkedList