-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.js
More file actions
58 lines (50 loc) · 1.2 KB
/
Queue.js
File metadata and controls
58 lines (50 loc) · 1.2 KB
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
class Queue {
constructor() {
this.items = [];
this.front = 0;
this.rear = 0;
}
// Add an item to the rear of the queue
enqueue(item) {
this.items[this.rear] = item;
this.rear++;
}
// Remove and return the item at the front of the queue
dequeue() {
if (this.isEmpty()) {
throw new Error("Queue is empty");
}
const removedItem = this.items[this.front];
this.front++;
return removedItem;
}
// Return the item at the front of the queue without removing it
peek() {
if (this.isEmpty()) {
throw new Error("Queue is empty");
}
return this.items[this.front];
}
// Check if the queue is empty
isEmpty() {
return this.front === this.rear;
}
// Return the number of items in the queue
size() {
return this.rear - this.front;
}
// Empty the queue
clear() {
this.items = [];
this.front = 0;
this.rear = 0;
}
}
// Example usage:
const queue = new Queue();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
console.log(queue.peek()); // 10
queue.dequeue();
console.log(queue.peek()); // 20