队列(Queue)是插入操作限定在表的尾部而其它操作限定在表的头部进行的线性表。把进行插入操作的表尾称为队尾(Rear),把进行其它操作的头部称为队头(Front)。当对列中没有数据元素时称为空对列(Empty Queue)。
队列通常记为:Q= (a1,a2,…,an),a1为队头元素,an为队尾元素。元素按照a1,a2,…,an的次序依次入队,出队的次序与入队相同,即a1第一个出队,an最后一个出队。所以,对列的操作是按照先进先出(First In First Out)或后进后出( Last In Last Out)的原则进行的,因此,队列又称为FIFO表或LILO表。
队列的常用操作有:
1、构造一个空队列:InitQueue()//在C#中可以使用构造函数来实现
2、清空队列:ClearQueue()
3、判断队列是否为空:IsEmpty()
4、判断队列是否已满:IsFull()
5、求队列长度:QueueLength()
6、入队操作:In()
7、出队操作:Out()
8、得到队头元素:GetHead()
下面给出一个实现顺序栈的源代码
- using System;
- class Queue
- {
- object[] data; //数据元素
- int maxsize; //最大容量
- int front; //指向队头
- int rear; //指向队尾
- //初始化队列
- public Queue(int size)
- {
- this.maxsize = size;
- data = new object[size];
- front = rear = -1;
- }
- //最大容量属性
- public int MaxSize
- {
- get
- {
- return this.maxsize;
- }
- set
- {
- this.maxsize = value;
- }
- }
- //队尾属性
- public int Rear
- {
- get
- {
- return this.rear;
- }
- }
- //队头属性
- public int Front
- {
- get
- {
- return this.front;
- }
- }
- //数据属性
- public object this[int index]
- {
- get
- {
- return data[index];
- }
- }
- //获得队列的长度
- public int GetQueueLength()
- {
- return rear - front;
- }
- //判断队列是否满
- public bool IsFull()
- {
- if (GetQueueLength() == maxsize)
- return true;
- else
- return false;
- }
- //判断队列是否为空
- public bool IsEmpty()
- {
- if (rear == front)
- return true;
- else
- return false;
- }
- //清空队列
- public void ClearQueue()
- {
- rear = front = -1;
- }
- //入队
- public void In(object e)
- {
- if (IsFull())
- {
- Console.WriteLine("队列已满!");
- return;
- }
- data[++rear] = e;
- }
- //出队
- public object Out()
- {
- if (IsEmpty())
- {
- Console.WriteLine("队列为空!");
- return null;
- }
- if (rear - front > 0)
- {
- object tmp = data[++front];
- return tmp;
- }
- else
- {
- Console.WriteLine("全出队了!");
- ClearQueue();
- return null;
- }
- }
- //获得队头元素
- public object GetHead()
- {
- if (IsEmpty())
- {
- Console.WriteLine("队列为空!");
- return null;
- }
- return data[front + 1];
- }
- }
- class Test
- {
- static void Main()
- {
- Queue q = new Queue(5);
- int rdNum;
- Random rd = new Random();
- while (!q.IsFull())
- {
- rdNum = rd.Next(10, 100);
- q.In(rdNum);
- Console.WriteLine("{0}入队,队列元素个数:{1}", rdNum, q.GetQueueLength());
- }
- Console.WriteLine("***************************");
- while (!q.IsEmpty())
- {
- Console.WriteLine("{0}出队,队列元素个数:{1}", q.Out(), q.GetQueueLength());
- }
- }
- }
运行结果:
23入队,队列元素个数:1
85入队,队列元素个数:2
28入队,队列元素个数:3
94入队,队列元素个数:4
55入队,队列元素个数:5
***************************
23出队,队列元素个数:4
85出队,队列元素个数:3
28出队,队列元素个数:2
94出队,队列元素个数:1
55出队,队列元素个数:0
请按任意键继续. . .