-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.js
More file actions
58 lines (51 loc) · 1.01 KB
/
Copy pathstack.js
File metadata and controls
58 lines (51 loc) · 1.01 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
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class Stack {
constructor() {
this.top = null;
this.length = 0;
}
push(val) {
const node = new Node(val);
if (this.top === null) {
this.top = node;
} else {
node.next = this.top;
this.top = node;
}
this.length++;
return node;
}
pop() {
if (this.top === null) return false;
const topNode = this.top;
this.top = this.top.next;
topNode.next = null;
this.length--;
return topNode;
}
peek() {
if (this.top === null) return undefined;
let topNode = this.top;
topNode.next = null;
return topNode;
}
isEmpty() {
if (this.length === 0) return true;
return false;
}
}
const stack = new Stack();
console.log(stack.push(1));
console.log(stack.push(2));
console.log(stack.push(3));
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.peek());
console.log(stack.isEmpty());
console.log(stack);