-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqfLoopQueue.cs
91 lines (76 loc) · 1.54 KB
/
qfLoopQueue.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
using System;
using Object = UnityEngine.Object;
/// <summary>
/// 可遍历的循环队列
/// from: http://www.cs.bu.edu/teaching/c/queue/array/types.html
/// </summary>
/// <typeparam name="T"></typeparam>
namespace qbfox
{
public class qfLoopQueue<T> : Object
{
private int _count;
private T[] _array;
private int _front;
private int _rear;
public qfLoopQueue(int count)
{
_count = count;
_array = new T[_count];
_front = 0;
_rear = 0;
}
public void Enqueue(T value)
{
if (IsFull())
throw new Exception("queue is full");
_array[_rear++] = value;
_rear = _rear >= _count ? 0 : _rear;
}
public T Dequeue()
{
if(ElementCount() == 0)
throw new Exception("queue is empty");
T result = _array[_front];
_array[_front--] = default(T);
_front = _front < 0 ? _count - 1 : _front;
return result;
}
public T GetElementAtIdx(int index)
{
if(index < 0 || index >= _count)
throw new Exception("index is out of bound");
int idx = _front + index;
if (idx > _count - 1)
idx -= _count;
return _array[idx];
}
public bool IsFull()
{
if (_front == 0 && _rear == _count - 1)
return true;
if (_rear == _front - 1)
return true;
return false;
}
public void Clear()
{
_front = 0;
_rear = 0;
_array = new T[_count];
}
public int ElementCount()
{
if (_front == _rear)
return 0;
if (_front < _rear)
return _rear - _front + 1;
else
return _count - (_front - _rear) + 1;
}
public int Length()
{
return _count;
}
}
}