-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathqueue.js
More file actions
48 lines (41 loc) · 895 Bytes
/
Copy pathqueue.js
File metadata and controls
48 lines (41 loc) · 895 Bytes
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
class Queue {
constructor() {
this.items = [];
}
// Add element to rear
enqueue(element) {
this.items.push(element);
}
// Remove element from front
dequeue() {
if (this.isEmpty()) return "Underflow";
return this.items.shift();
}
// Get front element
peek() {
if (this.isEmpty()) return "No elements in Queue";
return this.items[0];
}
// Check if empty
isEmpty() {
return this.items.length === 0;
}
// Size of queue
size() {
return this.items.length;
}
// Display queue
print() {
console.log(this.items.join(" <- "));
}
}
// Example usage:
const q = new Queue();
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.print(); // Output: 10 <- 20 <- 30
console.log(q.dequeue()); // Output: 10
console.log(q.peek()); // Output: 20
console.log(q.size()); // Output: 2
console.log(q.isEmpty()); // Output: false