实现循环队列的c#代码
时间: 2023-10-29 08:05:39 浏览: 45
以下是一个简单的循环队列的C#代码实现:
```csharp
public class CircularQueue<T>
{
private T[] _items;
private int _head;
private int _tail;
private int _size;
public CircularQueue(int capacity)
{
_items = new T[capacity];
_head = 0;
_tail = -1;
_size = 0;
}
public void Enqueue(T item)
{
if (_size == _items.Length)
{
throw new InvalidOperationException("Queue is full");
}
_tail = (_tail + 1) % _items.Length;
_items[_tail] = item;
_size++;
}
public T Dequeue()
{
if (_size == 0)
{
throw new InvalidOperationException("Queue is empty");
}
T item = _items[_head];
_head = (_head + 1) % _items.Length;
_size--;
return item;
}
public T Peek()
{
if (_size == 0)
{
throw new InvalidOperationException("Queue is empty");
}
return _items[_head];
}
public bool IsEmpty()
{
return _size == 0;
}
public bool IsFull()
{
return _size == _items.Length;
}
}
```