队列:
队列是一个有序列表,遵循先入先出原则,可以用数组或链表实现
使用场景
用于排队,按顺序执行
public static void Main(string[] args) { ArrayQueue<int> queue = new ArrayQueue<int>(1000); queue.Push(1); queue.Push(2); queue.Push(3); queue.Push(4); queue.Push(5); Console.WriteLine(queue.Pop()); Console.WriteLine(queue.Pop()); queue.Push(6); queue.Push(7); queue.Print(); Console.ReadKey(); }
数组队列
public class ArrayQueue<T> { private int _front = -1; //队首 private int _rear = -1; //队尾 private int _maxSize = 0; private T[] _arr = null; public ArrayQueue(int maxSize) { _maxSize = maxSize; _arr = new T[maxSize]; } public bool IsFull() { return _rear >= _maxSize - 1; } public bool IsEmpty() { return _front >= _rear; } public void Push(T n) { if (this.IsFull()) { throw new Exception("队列已满"); } _arr[++_rear] = n; } public T Pop() { if (this.IsEmpty()) { throw new Exception("队列已空"); } return _arr[++_front]; } public void Print() { if (this.IsEmpty()) { Console.WriteLine("队列已空"); return; } for (int i = _front + 1; i <= _rear; i++) { Console.WriteLine(i); } } }