- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathStackBasedQueue.cs
96 lines (83 loc) · 2.44 KB
/
StackBasedQueue.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
usingSystem;
usingSystem.Collections.Generic;
namespaceDataStructures.Queue;
/// <summary>
/// Implementation of a stack based queue. FIFO style.
/// </summary>
/// <remarks>
/// Enqueue is O(1) and Dequeue is amortized O(1).
/// </remarks>
/// <typeparam name="T">Generic Type.</typeparam>
publicclassStackBasedQueue<T>
{
privatereadonlyStack<T>input;
privatereadonlyStack<T>output;
/// <summary>
/// Initializes a new instance of the <see cref="StackBasedQueue{T}" /> class.
/// </summary>
publicStackBasedQueue()
{
input=newStack<T>();
output=newStack<T>();
}
/// <summary>
/// Clears the queue.
/// </summary>
publicvoidClear()
{
input.Clear();
output.Clear();
}
/// <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>
publicTDequeue()
{
if(input.Count==0&&output.Count==0)
{
thrownewInvalidOperationException("The queue contains no items.");
}
if(output.Count==0)
{
while(input.Count>0)
{
varitem=input.Pop();
output.Push(item);
}
}
returnoutput.Pop();
}
/// <summary>
/// Returns a boolean indicating whether the queue is empty.
/// </summary>
publicboolIsEmpty()=>input.Count==0&&output.Count==0;
/// <summary>
/// Returns a boolean indicating whether the queue is full.
/// </summary>
publicboolIsFull()=>false;
/// <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>
publicTPeek()
{
if(input.Count==0&&output.Count==0)
{
thrownewInvalidOperationException("The queue contains no items.");
}
if(output.Count==0)
{
while(input.Count>0)
{
varitem=input.Pop();
output.Push(item);
}
}
returnoutput.Peek();
}
/// <summary>
/// Adds an item at the last position in the queue.
/// </summary>
publicvoidEnqueue(Titem)=>input.Push(item);
}