-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.js
More file actions
73 lines (66 loc) · 1.18 KB
/
Copy pathStack.js
File metadata and controls
73 lines (66 loc) · 1.18 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
68
69
70
71
72
73
// Implementing a stack as a linked list
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor() {
this.top = null;
this.bottom = null;
this.length = 0;
}
peek() {
return this.top;
}
push(value) {
const newNode = new Node(value);
if (this.isEmpty()) {
this.bottom = this.top = newNode;
this.length++;
return this;
}
this.top.next = newNode;
this.top = newNode;
this.length++;
return this;
}
pop() {
if (!this.top) return null;
if (this.top === this.bottom) this.bottom = null;
this.top = this.top.next;
this.length--;
return this;
}
isEmpty() {
if (this.bottom === null) return true;
return false;
}
}
// Implementing a stack as an array
class ArrayStack {
constructor() {
this.array = [];
}
peek() {
return this.array[this.array.length - 1];
}
push(value) {
this.array.push(value);
return this;
}
pop() {
this.array.pop();
return this;
}
isEmpty() {
if (this.bottom === null) return true;
return false;
}
}
const st = new Stack();
st.push(1);
st.push(2);
st.push(3);
st.peek();