用数组来实现队列的一种比较好的方式是循环队列。
循环队列要注意的是队头和队尾的下标:
计算方式:
1.新的队头下标:front = (front+1)%array.Length
2.新的队尾下标:rear = (rear+1)%array.Length
3.(队尾下标+1)%数组长度 = 队头下标 时为队列满了
用数组实现循环队列的代码:
using System;namespace Test01
{public class MyQueue{private int[] array;private int front = 0;private int rear = 0;public MyQueue(int capacity){this.array = new int[capacity];}/// <summary>/// 入队/// </summary>public void EnQueue(int value){if((rear+1)%array.Length == front){Console.WriteLine("队列已满!");return;}array[rear] = value;rear = (rear + 1) % array.Length;}/// <summary>/// 出队/// </summary>public int DeQueue(){if (rear == front){Console.WriteLine("队列已空!");return -1;}int value = array[front];front = (front + 1) % array.Length;return value;}/// <summary>/// 打印队列/// </summary>public void Println(){for (int i = front; i!=rear; i=(i+1)%array.Length){Console.WriteLine(array[i]);}}}class Program{static void Main(string[] args){MyQueue myQueue = new MyQueue(6);myQueue.EnQueue(3);myQueue.EnQueue(5);myQueue.EnQueue(6);myQueue.EnQueue(8);myQueue.EnQueue(1);myQueue.DeQueue();myQueue.DeQueue();myQueue.DeQueue();myQueue.EnQueue(2);myQueue.EnQueue(4);myQueue.EnQueue(9);myQueue.Println();}}
}