C#队列(环形队列)
为什么需要环形队列
我们之前用数组实现队列的时候,当我们弹出队列中的元素后,会剩余很多的空间,这样非常的浪费,所以用环形队列能一定程度上减少空间的浪费。
代码实现如下
class MyQueue<T>
{
private int front;
private int last;
private int size;//最大容量
public int currCount;//当前元素个数
private T[] array;
//初始化队列
public MyQueue(int size)
{
array = new T[size];
front = 0;
last = 0;
this.size = size;
currCount = 0;
}
public void EnQueue(T t)
{
if (currCount==size)
{
throw new Exception("队列满了");
}
array[front] = t;
front = (front + 1) % size;
currCount++;
}
public T DeQueue()
{
if (currCount == 0)
{
throw new Exception("队列为空");
}
T tmp = array[last];
last = (last + 1) % size;
currCount--;
return tmp;
}
}
测试代码如下
class Program
{
static void Main(string[] args)
{
MyQueue<string> myQueue = new MyQueue<string>(5);
myQueue.EnQueue("第一");
myQueue.EnQueue("第二");
myQueue.EnQueue("第三");
myQueue.EnQueue("第四");
myQueue.EnQueue("第五");
myQueue.DeQueue();
myQueue.DeQueue();
myQueue.EnQueue("第六");
myQueue.EnQueue("第七");
myQueue.DeQueue();
myQueue.DeQueue();
myQueue.EnQueue("第八");
myQueue.EnQueue("第九");
myQueue.DeQueue();
myQueue.DeQueue();
myQueue.EnQueue("第十");
myQueue.EnQueue("第十一");
int curr = myQueue.currCount;
for (int i = 0; i < curr; i++)
{
Console.WriteLine(myQueue.DeQueue());
}
Console.ReadKey();
}
}
完整代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp20
{
class Program
{
static void Main(string[] args)
{
MyQueue<string> myQueue = new MyQueue<string>(5);
myQueue.EnQueue("第一");
myQueue.EnQueue("第二");
myQueue.EnQueue("第三");
myQueue.EnQueue("第四");
myQueue.EnQueue("第五");
myQueue.DeQueue();
myQueue.DeQueue();
myQueue.EnQueue("第六");
myQueue.EnQueue("第七");
myQueue.DeQueue();
myQueue.DeQueue();
myQueue.EnQueue("第八");
myQueue.EnQueue("第九");
myQueue.DeQueue();
myQueue.DeQueue();
myQueue.EnQueue("第十");
myQueue.EnQueue("第十一");
int curr = myQueue.currCount;
for (int i = 0; i < curr; i++)
{
Console.WriteLine(myQueue.DeQueue());
}
Console.ReadKey();
}
}
class MyQueue<T>
{
private int front;
private int last;
private int size;//最大容量
public int currCount;//当前元素个数
private T[] array;
//初始化队列
public MyQueue(int size)
{
array = new T[size];
front = 0;
last = 0;
this.size = size;
currCount = 0;
}
public void EnQueue(T t)
{
if (currCount==size)
{
throw new Exception("队列满了");
}
array[front] = t;
front = (front + 1) % size;
currCount++;
}
public T DeQueue()
{
if (currCount == 0)
{
throw new Exception("队列为空");
}
T tmp = array[last];
last = (last + 1) % size;
currCount--;
return tmp;
}
}
}