队列(queue)是只允许在一端进行插入操作,而在另一端进行删除操作的线性表。
队列是一种先进先出(First In First Out)的线性表,简称FIFO。允许插入的一端称为队尾,允许删除的一端称为队头。
- 队头(Front):允许删除的一端,又称队首。
- 队尾(Rear):允许插入的一端。
- 空队列:不包含任何元素的空表。
队列的数组实现
public class MyQueue<T>
{
private T[] items;
public int front;
public int rear;
private int count;
public int Count => count;
public int Capacity => items == null ? 0 : items.Length;
public MyQueue(int capacity = 2)
{
items = new T[capacity];
front = 0;
rear = 0;
count = 0;
}
public void Enqueue(T item)
{
if (count >= Capacity)
Expansion();
items[rear] = item;
rear = (rear + 1) % Capacity;
count++;
}
public T Dequeue()
{
if (count == 0)
throw new Exception("The queue is empty");
T value = items[front];
count--;
front = (front + 1) % Capacity;
return value;
}
public T Peek()
{
if (count == 0)
throw new Exception("Queue is empty");
return items[front];
}
private void Expansion()
{
int newCapacity = Capacity * 2;
T[] newItems = new T[newCapacity];
for (int i = front; i < count; i++)
newItems[i - front] = items[i % Capacity];
items = newItems;
front = 0;
rear = count;
}
}
队列的链表实现
//节点
public class Node<T>
{
public T value { get; set; }
public Node<T> next { get; set; }
public Node()
{
}
public Node(T value)
{
this.value = value;
}
}
//用链表实现队列
public class Queue<T>
{
public Node<T> front;
public Node<T> rear;
public int count;
public Queue()
{
count = 0;
}
//入队
public void Enqueue(T value)
{
Node<T> node = new Node<T>(value);
if (front == null)
{
front = node;
rear = front;
}
else
{
rear.next = node;
rear = node;
}
count++;
}
//出队
public T Dequeue()
{
if (front == null)
{
throw new Exception("Queue is empty");
}
else
{
T result = front.value;
front = front.next;
count--;
return result;
}
}
public void Show()
{
if (count == 0)
{
Console.WriteLine("队列空");
return;
}
else
{
Node<T> currentNode = front;
while (count != 0)
{
Console.WriteLine(currentNode.value);
currentNode = currentNode.next;
count--;
}
}
}