Repository navigation
Expand file tree
/
Copy pathCircularQueue.cs
More file actions
109 lines (98 loc) · 2.41 KB
/
Copy pathCircularQueue.cs
File metadata and controls
109 lines (98 loc) · 2.41 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
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
109
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
using System.Diagnostics;
namespace System.Threading.Internal
{
internal struct CircularQueue<T>
{
int put;
int get;
int size;
int depth;
T[] data;
public CircularQueue(int depth)
{
put = 0;
get = 0;
this.depth = depth;
data = new T[depth];
size = 0;
}
public bool Dequeue(ref T data)
{
if (size == 0)
return false;
data = this.data[get];
get++;
size--;
if (get >= depth)
get = 0;
return true;
}
public bool Peek(ref T data)
{
if (size == 0)
return false;
data = this.data[get];
return true;
}
public bool Enqueue(T data)
{
if (size >= depth)
return false;
this.data[put] = data;
put++;
size++;
if (put >= depth)
put = 0;
return true;
}
public bool Peek(ref T data, int index)
{
if (size <= index)
return false;
if (index >= depth)
index -= depth;
data = this.data[index];
return true;
}
public T this[int index]
{
get
{
T t = default;
if (Peek(ref t, index))
return t;
throw new Exception("Invalid Index");
}
}
public bool Contains(T data)
{
if (size == 0)
return false;
T dat = default;
for (int i = 0; i < size; i++)
{
if (Peek(ref dat, i))
{
if (dat.Equals(data))
return true;
}
}
return false;
}
public int Count => size;
public int Space => depth - size;
public bool IsFull => Space == 0;
public void Clear()
{
put = 0;
get = 0;
size = 0;
}
}
}