-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstacks.js
More file actions
98 lines (76 loc) · 1.73 KB
/
stacks.js
File metadata and controls
98 lines (76 loc) · 1.73 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//Stacks and Queues are used to access the first and last elements
//They are data structures built on lower level data structures
//Stacks
//Think of it like stacked plates vertically
//You can only access the top layer
//Last In First Out
//Fast Operations
//Fast peek
//Ordered
//Slow Lookup
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class linkStack {
constructor() {
this.top = this.node;
this.bottom = this.node;
this.length = 0;
}
peek() {
return this.top;
}
push(value) {
const newNode = new Node(value);
if(this.length == 0 ) {
this.top = newNode;
this.bottom = newNode;
} else {
const holdPointer = this.top;
this.top = newNode;
this.top.next = holdPointer
}
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;
}
}
/* const myStack = new linkStack();
myStack.push('udemy');
myStack.push('rolls-royce');
myStack.pop();
myStack.pop();
console.log(myStack); */
class arrStack {
constructor() {
this.arr = new Array();
}
peek() {
if (this.arr.length == 0) return undefined;
return this.arr[this.arr.length-1];
}
push(value) {
return this.arr.push(value);
}
pop() {
return this.arr.pop();
}
}
const myStack = new arrStack();
myStack.push('udemy');
myStack.push('rolls-royce');
myStack.pop();
myStack.pop();
console.log(myStack.peek());
console.log(myStack);