-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstacks.js
46 lines (40 loc) · 771 Bytes
/
stacks.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
// What is added last, is removed first.
class Node {
constructor(value) {
this.val = value
this.next = null
}
}
class Stack {
constructor () {
this.first = null
this.last = null
this.size = 0
}
push(val) {
let newNode = new Node(val)
if (!this.first) {
this.first = newNode
this.last = newNode
} else {
let temp = this.first
this.first = newNode
this.first.next = temp
}
this.size++
return this.size
}
pop() {
if (this.size === 0) return null
let temp = this.first
if (this.size === 1) {
this.first = null
this.last = null
}
this.first = this.first.next
this.length--
return this.temp
}
}
// Insertion is O(n)
// Removal is O(n)