-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.js
More file actions
39 lines (33 loc) · 669 Bytes
/
Copy pathstack.js
File metadata and controls
39 lines (33 loc) · 669 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
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class Stack {
constructor() {
this.first = null;
this.last = null;
this.size = 0;
}
push(val) {
const newNode = new Node(val);
if (!this.first) {
this.first = this.last = newNode;
} else {
[this.first, this.first.next] = [newNode, this.first];
}
return ++this.size;
}
pop() {
if (!this.first) return null;
const removedNode = this.first;
if (this.size === 1) {
this.first = this.last = null;
}
this.first = removedNode.next;
this.size--;
removedNode.next = null;
return removedNode;
}
}