队列
发表于:2025-10-13 | 分类: Dotnet
字数统计: 1.4k | 阅读时长: 7分钟 | 阅读量:

队列

基于 T[] array 实现。

  • head tail 双指针索引记录队首&队尾,可头尾相接循环使用array
  • size 支持动态扩容缩容
  • version 保证迭代时不修改集合
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\Queue.cs
namespace System.Collections.Generic
{
// FIFO对象集合
// 循环buffer,Enqueue/Dequeue为O(1)
public class Queue<T> : IEnumerable<T>, ICollection, IReadOnlyCollection<T>
{
private T[] _array;
private int _head; // 指向dequeue index
private int _tail; // 指向enqueue index
private int _size; // 元素数量
private int _version; // 版本号,用于标识迭代时确保没有修改集合

// 创建空queue,并使用默认grow factor
public Queue()
{
_array = Array.Empty<T>();
}

// 创建指定容量的queue,并使用默认grow factor
public Queue(int capacity)
{
ArgumentOutOfRangeException.ThrowIfNegative(capacity);
_array = new T[capacity];
}

// 用ICollection元素来填充queue
public Queue(IEnumerable<T> collection)
{
ArgumentNullException.ThrowIfNull(collection);

_array = EnumerableHelpers.ToArray(collection, out _size);
if (_size != _array.Length) _tail = _size;
}

// queue长度
public int Count
{
get { return _size; }
}

// 是否是同步的
bool ICollection.IsSynchronized
{
get { return false; }
}

// 锁对象
object ICollection.SyncRoot => this;

// 移除queue中所有对象
public void Clear()
{
if (_size != 0)
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
if (_head < _tail)
{
Array.Clear(_array, _head, _size);
}
else
{
Array.Clear(_array, _head, _array.Length - _head);
Array.Clear(_array, 0, _tail);
}
}

_size = 0;
}

_head = 0;
_tail = 0;
_version++;
}

// copy到array中
public void CopyTo(T[] array, int arrayIndex)
{
ArgumentNullException.ThrowIfNull(array);

if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}

if (array.Length - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}

int numToCopy = _size;
if (numToCopy == 0) return;

int firstPart = Math.Min(_array.Length - _head, numToCopy);
Array.Copy(_array, _head, array, arrayIndex, firstPart);
numToCopy -= firstPart;
if (numToCopy > 0)
{
Array.Copy(_array, 0, array, arrayIndex + _array.Length - _head, numToCopy);
}
}

// copy到array中
void ICollection.CopyTo(Array array, int index)
{
ArgumentNullException.ThrowIfNull(array);

if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}

if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}

int arrayLen = array.Length;
if (index < 0 || index > arrayLen)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}

if (arrayLen - index < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}

int numToCopy = _size;
if (numToCopy == 0) return;

try
{
int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy;
Array.Copy(_array, _head, array, index, firstPart);
numToCopy -= firstPart;

if (numToCopy > 0)
{
Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_IncompatibleArrayType, nameof(array));
}
}

// 入队
public void Enqueue(T item)
{
if (_size == _array.Length)
{
Grow(_size + 1);
}

_array[_tail] = item;
MoveNext(ref _tail);
_size++;
_version++;
}

// 返回队列的枚举器
public Enumerator GetEnumerator() => new Enumerator(this);

// private实现接口
IEnumerator<T> IEnumerable<T>.GetEnumerator() =>
Count == 0 ? SZGenericArrayEnumerator<T>.Empty :
GetEnumerator();

// private实现接口
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)this).GetEnumerator();

// 出队
public T Dequeue()
{
int head = _head;
T[] array = _array;

if (_size == 0)
{
ThrowForEmptyQueue();
}

T removed = array[head];
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
array[head] = default!;
}
MoveNext(ref _head);
_size--;
_version++;
return removed;
}

// 尝试出队
public bool TryDequeue([MaybeNullWhen(false)] out T result)
{
int head = _head;
T[] array = _array;

if (_size == 0)
{
result = default;
return false;
}

result = array[head];
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
array[head] = default!;
}
MoveNext(ref _head);
_size--;
_version++;
return true;
}

// 返回队首元素
public T Peek()
{
if (_size == 0)
{
ThrowForEmptyQueue();
}

return _array[_head];
}

// 尝试返回队首元素
public bool TryPeek([MaybeNullWhen(false)] out T result)
{
if (_size == 0)
{
result = default;
return false;
}

result = _array[_head];
return true;
}

// 是否包含item元素
public bool Contains(T item)
{
if (_size == 0)
{
return false;
}

if (_head < _tail)
{
return Array.IndexOf(_array, item, _head, _size) >= 0;
}

// We've wrapped around. Check both partitions, the least recently enqueued first.
return
Array.IndexOf(_array, item, _head, _array.Length - _head) >= 0 ||
Array.IndexOf(_array, item, 0, _tail) >= 0;
}

// 转换为array,元素顺序保持FIFO
public T[] ToArray()
{
if (_size == 0)
{
return Array.Empty<T>();
}

T[] arr = new T[_size];

if (_head < _tail)
{
Array.Copy(_array, _head, arr, 0, _size);
}
else
{
Array.Copy(_array, _head, arr, 0, _array.Length - _head);
Array.Copy(_array, 0, arr, _array.Length - _head, _tail);
}

return arr;
}

// 私有方法:增长或收缩buffer的capacity容量,必须保证 capacity >= size
private void SetCapacity(int capacity)
{
T[] newarray = new T[capacity];
if (_size > 0)
{
if (_head < _tail)
{
Array.Copy(_array, _head, newarray, 0, _size);
}
else
{
Array.Copy(_array, _head, newarray, 0, _array.Length - _head);
Array.Copy(_array, 0, newarray, _array.Length - _head, _tail);
}
}

_array = newarray;
_head = 0;
_tail = (_size == capacity) ? 0 : _size;
_version++;
}

// 移动指针
private void MoveNext(ref int index)
{
int tmp = index + 1;
if (tmp == _array.Length)
{
tmp = 0;
}
index = tmp;
}

// 抛出空queue异常
private void ThrowForEmptyQueue()
{
Debug.Assert(_size == 0);
throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue);
}

// 裁剪超出的容量,实际大小<array大小的0.9倍则裁剪为实际大小
public void TrimExcess()
{
int threshold = (int)(_array.Length * 0.9);
if (_size < threshold)
{
SetCapacity(_size);
}
}

// 确保容量最小为capacity,返回queue容量
public int EnsureCapacity(int capacity)
{
ArgumentOutOfRangeException.ThrowIfNegative(capacity);

if (_array.Length < capacity)
{
Grow(capacity);
}

return _array.Length;
}

// 容量增长为capacity
private void Grow(int capacity)
{
Debug.Assert(_array.Length < capacity);

const int GrowFactor = 2;
const int MinimumGrow = 4;

int newcapacity = GrowFactor * _array.Length;

if ((uint)newcapacity > Array.MaxLength) newcapacity = Array.MaxLength;

newcapacity = Math.Max(newcapacity, _array.Length + MinimumGrow);

if (newcapacity < capacity) newcapacity = capacity;

SetCapacity(newcapacity);
}

// 实现Queue枚举器,使用内部的version来确保迭代过程中未修改list
public struct Enumerator : IEnumerator<T>, IEnumerator
{
private readonly Queue<T> _q;
private readonly int _version;
private int _index; // -1 = not started, -2 = ended/disposed
private T? _currentElement;

internal Enumerator(Queue<T> q)
{
_q = q;
_version = q._version;
_index = -1;
_currentElement = default;
}

public void Dispose()
{
_index = -2;
_currentElement = default;
}

public bool MoveNext()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);

if (_index == -2)
return false;

_index++;

if (_index == _q._size)
{
_index = -2;
_currentElement = default;
return false;
}

T[] array = _q._array;
uint capacity = (uint)array.Length;

uint arrayIndex = (uint)(_q._head + _index);
if (arrayIndex >= capacity)
{
arrayIndex -= capacity; // wrap around if needed
}

_currentElement = array[arrayIndex];
return true;
}

public T Current
{
get
{
if (_index < 0)
ThrowEnumerationNotStartedOrEnded();
return _currentElement!;
}
}

private void ThrowEnumerationNotStartedOrEnded()
{
Debug.Assert(_index == -1 || _index == -2);
throw new InvalidOperationException(_index == -1 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded);
}

object? IEnumerator.Current
{
get { return Current; }
}

void IEnumerator.Reset()
{
if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -1;
_currentElement = default;
}
}
}
}
上一篇:
最佳实践
下一篇:
字典