-
Notifications
You must be signed in to change notification settings - Fork 5
/
13.Stacks.js
92 lines (70 loc) · 1.58 KB
/
13.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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// A LIFO (Last In First Out) data structure!
// The last element added to the stack will be the first element removed from the stack
// BIG O of STACKS
// Insertion - O(1)
// Removal - O(1)
// Searching - O(N)
// Access - O(N)
// LINKED LIST IMPLEMENTATION
class Node {
constructor(value){
this.value = value
this.next = null
}
}
class Stack {
constructor(){
this.first = null; // head
this.last = null; // tail
this.size = 0; // length
}
// add to the beginning - O(1) time complexity
// unshift
push(value) {
const newNode = new Node(value);
const currentFirst = this.first;
newNode.next = currentFirst
this.first = newNode
// this.size++
// if list was empty
if(!currentFirst) {
this.last = newNode
}
return ++this.size
}
// remove from the beginning - O(1) time complexity
// shift
pop() {
// if there is no element in the list
if(!this.first) {
return null
}
// if there is only one element in the list
if(!this.first.next) {
const currentFirst = this.first
this.first = this.last = null
this.size-
return currentFirst.value
}
const currentFirst = this.first;
const newFirst = currentFirst.next
this.first = newFirst
this.size--
return currentFirst.value
}
}
// ARRAY IMPLEMENTATION
class Stack_ {
constructor() {
this.stack = []
}
push(element) {
this.stack.push(element)
}
pop(element) {
return this.stack.pop()
}
peek() {
return this.stack[this.stack.length - 1]
}
}