forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayBasedQueue.cs
108 lines (93 loc) · 2.96 KB
/
ArrayBasedQueue.cs
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using System;
namespace DataStructures.Queue
{
/// <summary>
/// Implementation of an array based queue. FIFO style.
/// </summary>
/// <typeparam name="T">Generic Type.</typeparam>
public class ArrayBasedQueue<T>
{
private readonly T[] queue;
private int endIndex;
private bool isEmpty;
private bool isFull;
private int startIndex;
/// <summary>
/// Initializes a new instance of the <see cref="ArrayBasedQueue{T}" /> class.
/// </summary>
public ArrayBasedQueue(int capacity)
{
queue = new T[capacity];
Clear();
}
/// <summary>
/// Clears the queue.
/// </summary>
public void Clear()
{
startIndex = 0;
endIndex = 0;
isEmpty = true;
isFull = false;
}
/// <summary>
/// Returns the first item in the queue and removes it from the queue.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the queue is empty.</exception>
public T Dequeue()
{
if (IsEmpty())
{
throw new InvalidOperationException("There are no items in the queue.");
}
var dequeueIndex = endIndex;
endIndex++;
if (endIndex >= queue.Length)
{
endIndex = 0;
}
isFull = false;
isEmpty = startIndex == endIndex;
return queue[dequeueIndex];
}
/// <summary>
/// Returns a boolean indicating whether the queue is empty.
/// </summary>
public bool IsEmpty() => isEmpty;
/// <summary>
/// Returns a boolean indicating whether the queue is full.
/// </summary>
public bool IsFull() => isFull;
/// <summary>
/// Returns the first item in the queue and keeps it in the queue.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the queue is empty.</exception>
public T Peek()
{
if (IsEmpty())
{
throw new InvalidOperationException("There are no items in the queue.");
}
return queue[endIndex];
}
/// <summary>
/// Adds an item at the last position in the queue.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the queue is full.</exception>
public void Enqueue(T item)
{
if (IsFull())
{
throw new InvalidOperationException("The queue has reached its capacity.");
}
queue[startIndex] = item;
startIndex++;
if (startIndex >= queue.Length)
{
startIndex = 0;
}
isEmpty = false;
isFull = startIndex == endIndex;
}
}
}