-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataStructure.js
52 lines (49 loc) · 962 Bytes
/
dataStructure.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
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class Queue {
constructor() {
this.top = null;
this.currEnqueuedNode = null;
this.size = 0;
}
enqueue(data) {
const newNode = new Node(data);
if (!this.top) this.top = newNode;
else this.currEnqueuedNode.next = newNode;
this.currEnqueuedNode = newNode;
this.size += 1;
}
dequeue() {
const temp = this.top?.data;
this.top = this.top?.next;
this.size += -1;
return temp;
}
forEach(callback, data = this.top) {
if (!data) return;
callback(data);
this.forEach(callback, data.next);
}
}
class Stack {
constructor() {
this.top = null;
}
isEmpty() {
return this.top === null;
}
push(data) {
const newNode = new Node(data);
newNode.next = this.top;
this.top = newNode;
}
pop() {
if (this.isEmpty()) return;
this.top = this.top.next;
}
}
export { Queue, Stack };