-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStacksQueues.js
99 lines (92 loc) · 1.95 KB
/
StacksQueues.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
93
94
95
96
97
98
99
class Node {
constructor(val){
this.val = val;
this.next = null;
this.prev = null;
}
}
// Stack => Needs to have constant time and is FILO => Two fxns push and pop
class Stack {
constructor(){
this.head = null;
this.tail = null;
this.length = 0;
}
push = val => {
let newNode = new Node(val);
if (!this.head) {
this.head = newNode;
this.tail = this.head;
} else {
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
}
this.length++;
return this;
};
pop = () => {
if (!this.length) return undefined;
let oldTail = this.tail;
if (oldTail.prev) {
let newTail = this.tail.prev;
newTail.next = null;
this.tail = newTail;
this.length--;
} else {
this.head = null;
this.tail = null;
this.length = 0
}
oldTail.prev = null;
return oldTail;
};
}
// Queue => Needs to have constant time and is FIFO => Two fxns push and pop
class Queue {
constructor(){
this.head = null;
this.tail = null;
this.length = 0;
}
push = val => {
let newNode = new Node(val);
if (!this.head) {
this.head = newNode;
this.tail = this.head;
} else {
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
}
this.length++;
return this;
};
DLLPop = () => {
if (!this.length) return undefined;
let oldTail = this.tail;
if (oldTail.prev) {
let newTail = this.tail.prev;
newTail.next = null;
this.tail = newTail;
this.length--;
} else {
this.head = null;
this.tail = null;
this.length = 0
}
oldTail.prev = null;
return oldTail;
};
pop = () => {
if(!this.head) return undefined;
if(this.length === 1){
return this.DLLPop() ? true : false;
}
let newHead = this.head.next;
newHead.prev = null;
this.head = newHead;
this.length--
return true;
};
}