-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.js
48 lines (46 loc) · 998 Bytes
/
stack.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
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
// stack using a linked list
class Stack {
constructor(value) {
this.first = value;
this.last = null;
this.size = 0;
}
// O(1)
push(val) {
let newNode = new Node(val)
if (!this.first) { // catch if there is nothing in linked list to start
this.first = newNode;
this.last = newNode;
} else {
let temp = this.first
this.first = newNode;
this.first.next = temp;
}
return ++this.size;
}
// O(1)
pop() {
if (!this.first) return null; // nothing in stack to pop
let temp = this.first;
if (this.size === 1) { // if there is only 1 node
this.last = null;
}
this.first = this.first.next;
this.size -= 1;
return temp.value;
}
}
let stack = new Stack();
stack.push('First');
stack.push('Second');
stack.push('Third');
stack.pop(); // third
stack.pop(); // second
stack.pop(); // first
stack.pop(); // null