Skip to content

Commit cbc1abf

Browse files
Create Deque Implementation.js
1 parent 55ff0ad commit cbc1abf

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed

Deque/Deque Implementation.js

+96
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
class Node {
2+
constructor(value) {
3+
this.data = value;
4+
this.prev = null;
5+
this.next = null;
6+
}
7+
}
8+
9+
class Dequeue {
10+
constructor() {
11+
this.front = null;
12+
this.rear = null;
13+
}
14+
15+
// Add to the front of the dequeue
16+
pushFront(value) {
17+
const newNode = new Node(value);
18+
if (!this.front) {
19+
this.front = this.rear = newNode;
20+
} else {
21+
newNode.next = this.front;
22+
this.front.prev = newNode;
23+
this.front = newNode;
24+
}
25+
}
26+
27+
// Add to the back of the dequeue
28+
pushBack(value) {
29+
const newNode = new Node(value);
30+
if (!this.rear) {
31+
this.front = this.rear = newNode;
32+
} else {
33+
newNode.prev = this.rear;
34+
this.rear.next = newNode;
35+
this.rear = newNode;
36+
}
37+
}
38+
39+
// Remove from the front of the dequeue
40+
popFront() {
41+
if (!this.front) {
42+
console.log("Dequeue is empty");
43+
return null;
44+
}
45+
const value = this.front.data;
46+
this.front = this.front.next;
47+
if (this.front) {
48+
this.front.prev = null;
49+
} else {
50+
this.rear = null;
51+
}
52+
return value;
53+
}
54+
55+
// Remove from the back of the dequeue
56+
popBack() {
57+
if (!this.rear) {
58+
console.log("Dequeue is empty");
59+
return null;
60+
}
61+
const value = this.rear.data;
62+
this.rear = this.rear.prev;
63+
if (this.rear) {
64+
this.rear.next = null;
65+
} else {
66+
this.front = null;
67+
}
68+
return value;
69+
}
70+
71+
// Check if the dequeue is empty
72+
isEmpty() {
73+
return this.front === null;
74+
}
75+
76+
// Get the front element
77+
getFront() {
78+
return this.front ? this.front.data : null;
79+
}
80+
81+
// Get the rear element
82+
getRear() {
83+
return this.rear ? this.rear.data : null;
84+
}
85+
}
86+
87+
// Example usage:
88+
const dequeue = new Dequeue();
89+
dequeue.pushFront(10);
90+
dequeue.pushBack(20);
91+
dequeue.pushFront(5);
92+
console.log("Front element:", dequeue.getFront()); // 5
93+
console.log("Rear element:", dequeue.getRear()); // 20
94+
console.log("Popped from front:", dequeue.popFront()); // 5
95+
console.log("Popped from back:", dequeue.popBack()); // 20
96+
console.log("Is dequeue empty?", dequeue.isEmpty()); // false

0 commit comments

Comments
 (0)