一、代码实现循环队列
思路:使用数组存储数据,两个指针保存队列头尾
问题:https://leetcode-cn.com/problems/design-circular-queue/
设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。
循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。
你的实现应该支持如下操作:
MyCircularQueue(k): 构造器,设置队列长度为 k 。
Front: 从队首获取元素。如果队列为空,返回 -1 。
Rear: 获取队尾元素。如果队列为空,返回 -1 。
enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
isEmpty(): 检查循环队列是否为空。
isFull(): 检查循环队列是否已满。
示例:
MyCircularQueue circularQueue = new MycircularQueue(3); // 设置长度为 3
circularQueue.enQueue(1); // 返回 true
circularQueue.enQueue(2); // 返回 true
circularQueue.enQueue(3); // 返回 true
circularQueue.enQueue(4); // 返回 false,队列已满
circularQueue.Rear(); // 返回 3
circularQueue.isFull(); // 返回 true
circularQueue.deQueue(); // 返回 true
circularQueue.enQueue(4); // 返回 true
circularQueue.Rear(); // 返回 4
提示:
所有的值都在 0 至 1000 的范围内;
操作数将在 1 至 1000 的范围内;
请不要使用内置的队列库。
GitHub实现:https://github.com/JonathanZxxxx/LeetCode/blob/master/MyCircularQueue.cs
Blog:https://www.cnblogs.com/zxxxx/
public class MyCircularQueue
{
//保存数据
private int[] data;
//头指针
private int head;
//尾指针
private int tail;
//队列长度
private int size;
//初始化
public MyCircularQueue(int k)
{
data = new int[k];
head = tail = -1;
size = k;
}
//插入
public bool EnQueue(int value)
{
if (IsFull()) return false;
if (IsEmpty()) head = 0;
tail = (tail + 1) % size;
data[tail] = value;
return true;
}
//删除
public bool DeQueue()
{
if (IsEmpty()) return false;
if (head == tail)
{
head = tail = -1;
return true;
}
head = (head + 1) % size;
return true;
}
//返回头
public int Front()
{
if (IsEmpty()) return -1;
return data[head];
}
//返回尾
public int Rear()
{
if (IsEmpty()) return -1;
return data[tail];
}
//判断队列是否已满
public bool IsFull()
{
return (tail + 1) % size == head;
}
//判断队列是否为空
public bool IsEmpty()
{
return head == -1;
}
}
二、C# Queue队列用法
//Queue队列就是先进先出。它并没有实现 IList,ICollection。所以它不能按索引访问元素,不能使用Add和Remove。下面是 Queue的一些方法和属性
//Enqueue():在队列的末端添加元素
//Dequeue():在队列的头部读取和删除一个元素,注意,这里读取元素的同时也删除了这个元素。如果队列中不再有任何元素。就抛出异常
//Peek():在队列的头读取一个元素,但是不删除它
//Count:返回队列中的元素个数
//TrimExcess():重新设置队列的容量,因为调用Dequeue方法读取删除元素后不会重新设置队列的容量。
//Contains():确定某个元素是否在队列中
//CopyTo():把元素队列复制到一个已有的数组中
//ToArray():返回一个包含元素的新数组
var queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
var q1 = queue.Peek();
var q2 = queue.Count;
var q3 = queue.Dequeue();
var q4 = queue.Count;
queue.TrimExcess();
var q5 = queue.Count;
var q6 = queue.Contains(2);