C#算法学习之队列
- 首先使用数组模拟队列的情况。假设我们有一组加密过的数,解密的要求是:去掉第1个数,把第2个数放到这组数的末尾,然后把第3个数除去,将第4个数放到末尾・・・直到剩下最后一个数,将最后一个数删掉。然后按删除的顺序,把删除的数添加到数组。
- 下面看代码:
class Program
{
static void Main(string[] args)
{
int[] q = new int[9] {9,2,4,6,1,7,3,5,8};//待解密的数组
int[] qs = new int[100];//定义一个空数组,把待解密数组存进去。
for(int i = 0;i < 100;i ++)
{
if (i <= q.Length-1)
{
qs[i] = q[i];
}
}
int head = 0;
int tail = 9;//为了避免队首和队尾重合,故意把队尾下标后移一位。
while(head < tail)
{
Console.Write(qs[head]+", ");//打印队首
head++;//去掉队首,数组所有下标前进一位
qs[tail] = qs[head];//把新队首放到队尾
tail++;//队尾下标后移一位
head++;//队首下标前进一位
}
Console.Read();
}
}
运行结果:9 4 1 3 8 6 5 7 2
- 主要思想:First In First Out,把队首先出,先出的队首放到队尾,然后重复操作。
- 使用队列Queue来表示,看如下代码
class Program
{
static void Main(string[] args)
{
Queue<int> queue = new Queue<int>();
int[]list = new int[] { 9, 2, 4, 6, 1, 7, 3, 5, 8};
for(int i=0;i<list.Length;i++)
{
queue.Enqueue(list[i]);
}
for(int i =0;i<list.Length;i++)
{
Console.Write(queue.Peek() + " ");//打印队首第一个元素
queue.Dequeue();//队首出队
queue.Enqueue(queue.Dequeue());//把新队首出队且放到末尾
if(queue.Count<=1)
{
Console.Write(queue.Peek() + " ");//打印队首第一个元素
return;
}
}
}
}
运行结果:9 4 1 3 8 6 5 7 2