本文介绍C#实现队列结构定义、入队、出队操作 1、队列结构定义 /// /// 队列结构体定义 /// public struct SqQueue { public int[] data;//队列存放的元素 public int front, real;//队头和队尾指针 }
2、队列初始化 /// /// 队列初始化 /// /// static void InitQueue(ref SqQueue Q) { Q.real = Q.front=0; } 3、判断队列是否为空 /// /// 判断队列是否为空 /// /// /// static bool isEmpty( SqQueue Q) { if (Q.front == Q.real) { return true; } else return false; } 4、入队 /// /// 入队 /// /// /// /// static bool EnQueue(ref SqQueue Q,int x) { if ((Q.real+1)%MAXSizeQ.front) { return false; } Q.data[Q.real] = x; Q.real = (Q.real + 1) % MAXSize; return true; } 5、出队 static bool DeQueue(ref SqQueue Q, ref int x) { if (Q.realQ.front) { return false; } x = Q.data[Q.front]; Q.front = (Q.front + 1) % MAXSize; return true; } 6、实际main函数测试 static void Main(string[] args) { SqQueue Q = new SqQueue(); Q.data = new int[MAXSize]; int x = 0; //初始化队列 InitQueue(ref Q); while (x!=999) { Console.WriteLine(“请输入入队元素:”); x = int.Parse(Console.ReadLine()); if ((Q.real+1)%MAXSize==Q.front) { Console.WriteLine(“队列已满。”); break; } if (x!=999) EnQueue(ref Q, x); } //出队 Console.WriteLine(“出元素如下:”); while (!isEmpty(Q)) { DeQueue(ref Q,ref x); Console.WriteLine(x); }
Console.ReadLine();
}