Skip to content

Commit 6b0bdd8

Browse files
Merge pull request #572 from AnirudhPhophalia/patch-2
Implement Queue class with basic operations using typescript
2 parents 41955c0 + cdbac79 commit 6b0bdd8

File tree

1 file changed

+46
-0
lines changed
  • TypeScript/data_structures/queue

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Queue<T> {
2+
private items: T[] = [];
3+
4+
// Add element to rear
5+
enqueue(element: T): void {
6+
this.items.push(element);
7+
}
8+
9+
// Remove element from front
10+
dequeue(): T | string {
11+
if (this.isEmpty()) return "Underflow";
12+
return this.items.shift()!;
13+
}
14+
15+
// Get front element
16+
peek(): T | string {
17+
if (this.isEmpty()) return "No elements in Queue";
18+
return this.items[0];
19+
}
20+
21+
// Check if empty
22+
isEmpty(): boolean {
23+
return this.items.length === 0;
24+
}
25+
26+
// Size of queue
27+
size(): number {
28+
return this.items.length;
29+
}
30+
31+
// Display queue
32+
print(): void {
33+
console.log(this.items.join(" <- "));
34+
}
35+
}
36+
37+
// Example usage:
38+
const q = new Queue<number>();
39+
q.enqueue(5);
40+
q.enqueue(15);
41+
q.enqueue(25);
42+
q.print(); // Output: 5 <- 15 <- 25
43+
console.log(q.dequeue()); // Output: 5
44+
console.log(q.peek()); // Output: 15
45+
console.log(q.size()); // Output: 2
46+
console.log(q.isEmpty()); // Output: false

0 commit comments

Comments
 (0)