-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstack.js
76 lines (61 loc) · 1.38 KB
/
stack.js
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
68
69
70
71
72
73
74
75
76
class Node {
constructor (val) {
this.val = val;
this.next = null;
}
}
class Stack {
constructor () {
this.size = 0;
this.first = null;
this.last = null;
}
push (val) {
const node = new Node(val);
if (this.size === 0) {
this.first = this.last = node;
} else {
node.next = this.first;
this.first = node;
}
return ++this.size;
}
pop () {
if (this.size === 0) {
return null;
}
const node = this.first;
if (this.size === 1) {
this.first = this.last = null;
} else {
this.first = this.first.next;
}
this.size--;
return node;
}
print () {
const arr = [];
let node = this.first;
while (node) {
arr.push(node.val);
node = node.next;
}
console.log(arr);
}
}
const stack = new Stack();
// push
console.log(stack.push('First'));
console.log(stack.push('Second'));
console.log(stack.push('Third'));
console.log(stack.push('Fourth'));
console.log(stack.push('Fifth'));
console.log(stack.push('Sixth'));
console.log(stack.push('Seventh'));
console.log(stack.push('Eighth'));
console.log(stack.push('Ninth'));
// print
stack.print();
// pop
console.log(stack.pop());
console.log(stack.pop());