-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution4.cs
More file actions
81 lines (68 loc) · 2.26 KB
/
Solution4.cs
File metadata and controls
81 lines (68 loc) · 2.26 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cSharpSolutions
{
internal class Solution4
{
private class CircularQueue<T>
{
private T[] items;
private int head, tail, count, capacity;
public CircularQueue(int capacity = 4)
{
this.capacity = capacity;
items = new T[capacity];
head = tail = count = 0;
}
public void Enqueue(T item)
{
if (count == capacity) Resize(capacity * 2);
items[tail] = item;
tail = (tail + 1) % capacity;
count++;
}
public T Dequeue()
{
if (IsEmpty()) throw new InvalidOperationException("Queue is empty.");
T value = items[head];
head = (head + 1) % capacity;
count--;
return value;
}
public T Peek()
{
if (IsEmpty()) throw new InvalidOperationException("Queue is empty.");
return items[head];
}
public bool IsEmpty() => count == 0;
public int Count() => count;
private void Resize(int newCapacity)
{
T[] newArr = new T[newCapacity];
for (int i = 0; i < count; i++)
newArr[i] = items[(head + i) % capacity];
items = newArr;
head = 0;
tail = count;
capacity = newCapacity;
}
}
public static void Run()
{
Console.WriteLine("=== Solution 4: Circular Queue ===");
var queue = new CircularQueue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);
Console.WriteLine($"Queue count: {queue.Count()}, front: {queue.Peek()}");
Console.WriteLine("Dequeueing elements:");
while (!queue.IsEmpty())
Console.WriteLine(queue.Dequeue());
Console.WriteLine($"Queue empty? {queue.IsEmpty()}");
Console.WriteLine("\nSolution 4 complete");
}
}
}