Skip to content

Commit 9c3bc16

Browse files
authored
Create Queue.js
1 parent e009cd4 commit 9c3bc16

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

03-DataStructures/Queue.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Queue {
2+
constructor() {
3+
this.items = [];
4+
this.front = 0;
5+
this.rear = 0;
6+
}
7+
8+
// Add an item to the rear of the queue
9+
enqueue(item) {
10+
this.items[this.rear] = item;
11+
this.rear++;
12+
}
13+
14+
// Remove and return the item at the front of the queue
15+
dequeue() {
16+
if (this.isEmpty()) {
17+
throw new Error("Queue is empty");
18+
}
19+
const removedItem = this.items[this.front];
20+
this.front++;
21+
return removedItem;
22+
}
23+
24+
// Return the item at the front of the queue without removing it
25+
peek() {
26+
if (this.isEmpty()) {
27+
throw new Error("Queue is empty");
28+
}
29+
return this.items[this.front];
30+
}
31+
32+
// Check if the queue is empty
33+
isEmpty() {
34+
return this.front === this.rear;
35+
}
36+
37+
// Return the number of items in the queue
38+
size() {
39+
return this.rear - this.front;
40+
}
41+
42+
// Empty the queue
43+
clear() {
44+
this.items = [];
45+
this.front = 0;
46+
this.rear = 0;
47+
}
48+
}
49+
50+
// Example usage:
51+
const queue = new Queue();
52+
queue.enqueue(10);
53+
queue.enqueue(20);
54+
queue.enqueue(30);
55+
console.log(queue.peek()); // 10
56+
queue.dequeue();
57+
console.log(queue.peek()); // 20
58+

0 commit comments

Comments
 (0)