C#概况
循环队列
队首出,队尾进,首位相接(保持具有至少一个空位的状态)
循环队列就是将队列存储空间的最后一个位置绕到第一个位置,形成逻辑上的环状空间,供队列循环使用。在循环队列结构中,当存储空间的最后一个位置已被使用而再要进入队运算时,只需要存储空间的第一个位置空闲,便可将元素加入到第一个位置,即将存储空间的第一个位置作为队尾。循环队列可以更简单防止伪溢出的发生,但队列大小是固定的。
在循环队列中,当队列为空时,有front=rear,而当所有队列空间全占满时,也有front=rear。为了区别这两种情况,规定循环队列最多只能有MaxSize-1个队列元素,当循环队列中只剩下一个空存储单元时,队列就已经满了。因此,队列判空的条件是front=rear,而队列判满的条件是front=(rear+1)%QueueSize。
循环队列的重要公式
QueueSize:开辟数组大小
判断队满条件:
(rear+1)%QueueSize==front
计算队列长度:
(rear-front+QueueSize)%QueueSize
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _01_1_queue //项目名
{
class Program
{
public class MyQueue
{
public int front { get; set; }
public int rear { get; set; }
public int []data { get; set; }
public int maxnum;
public MyQueue(int n) //建立数组
{
this.front = 0;
this.rear = 0;
this.maxnum = n;
this.data = new int[maxnum];
}
public void PrintQueue()
{
int i = this.front;
int j = this.rear;
if (this.rear == this.front)
{
Console.WriteLine("Empty!");
return;
}
while ((this.rear ) % this.maxnum != this.front)// 还有未打印完的地方
{
Console.WriteLine(this.data[this.front]);
this.front = (this.front + 1) % this.maxnum; //错到下一位置
}
this.front = i;
this.rear = j;
}
public int QueueLength()
{
return (this.rear - this.front + maxnum) % maxnum;//长度公式
}
public void AddNode(int n)
{
if((this.rear+1)%maxnum ==this.front)
{
Console.WriteLine("Full!");
return;
}
else
{
this.data[this.rear] = n;
this.rear = (this.rear + 1) % this.maxnum;
//Console.WriteLine(this.rear);
}
}
public void DeleteNode()
{
if (this.rear == this.front)
{
Console.WriteLine("Empty");
return;
}
else
{
this.front = (this.front + 1) % this.maxnum;
}
}
}
static void Main(string[] args) //test
{
MyQueue queue = new MyQueue(7);
queue.AddNode(0);
queue.AddNode(1);
queue.AddNode(2);
queue.AddNode(3);
queue.AddNode(4);
queue.AddNode(5);
/* */
queue.AddNode(6);
queue.PrintQueue();
queue.DeleteNode();
queue.DeleteNode();
queue.PrintQueue();
}
}
}