forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeque Implementation.js
96 lines (87 loc) · 2.3 KB
/
Deque Implementation.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
class Node {
constructor(value) {
this.data = value;
this.prev = null;
this.next = null;
}
}
class Dequeue {
constructor() {
this.front = null;
this.rear = null;
}
// Add to the front of the dequeue
pushFront(value) {
const newNode = new Node(value);
if (!this.front) {
this.front = this.rear = newNode;
} else {
newNode.next = this.front;
this.front.prev = newNode;
this.front = newNode;
}
}
// Add to the back of the dequeue
pushBack(value) {
const newNode = new Node(value);
if (!this.rear) {
this.front = this.rear = newNode;
} else {
newNode.prev = this.rear;
this.rear.next = newNode;
this.rear = newNode;
}
}
// Remove from the front of the dequeue
popFront() {
if (!this.front) {
console.log("Dequeue is empty");
return null;
}
const value = this.front.data;
this.front = this.front.next;
if (this.front) {
this.front.prev = null;
} else {
this.rear = null;
}
return value;
}
// Remove from the back of the dequeue
popBack() {
if (!this.rear) {
console.log("Dequeue is empty");
return null;
}
const value = this.rear.data;
this.rear = this.rear.prev;
if (this.rear) {
this.rear.next = null;
} else {
this.front = null;
}
return value;
}
// Check if the dequeue is empty
isEmpty() {
return this.front === null;
}
// Get the front element
getFront() {
return this.front ? this.front.data : null;
}
// Get the rear element
getRear() {
return this.rear ? this.rear.data : null;
}
}
// Example usage:
const dequeue = new Dequeue();
dequeue.pushFront(10);
dequeue.pushBack(20);
dequeue.pushFront(5);
console.log("Front element:", dequeue.getFront()); // 5
console.log("Rear element:", dequeue.getRear()); // 20
console.log("Popped from front:", dequeue.popFront()); // 5
console.log("Popped from back:", dequeue.popBack()); // 20
console.log("Is dequeue empty?", dequeue.isEmpty()); // false