using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QueueTest
{
public struct pqItem {
public int priority;
public string name;
}
/// <summary>
/// 源自Queue的优先队列
/// </summary>
class PQueue:Queue
{
public PQueue() {
}
/// <summary>
/// 重写出队
/// </summary>
/// <returns></returns>
public override object Dequeue()
{
object[] items;//数组
int min;//数字越小优先级越大
items = this.ToArray();//队列元素复制到数组
min = ((pqItem)items[0]).priority;//默认数组索引为0的优先级最大
//
for (int i = 0; i <= items.GetUpperBound(0); i++)
if (((pqItem)items[i]).priority<min)
{
min = ((pqItem)items[i]).priority;//优先级重新设置
}
this.Clear();//从队列中移除所有对象
int x2;
//对数组循环遍历
for (x2 = 0; x2 < items.GetUpperBound(0); x2++)
//如果数组中找到优先级最高的(且名字不为空) 就进队
if (((pqItem)items[x2]).priority ==min&&((pqItem)items[x2]).name!="")
this.Enqueue(items[x2]); //进队
Console.WriteLine(this.Count); //值为1
return base.Dequeue();//先进先出
}
static void Main() {
PQueue erwait = new PQueue();//创建一个队列
pqItem[] erPatient = new pqItem[3];//创建pqItem的数组
pqItem nextPatient;//下一个
erPatient[0].name = "Joe Smith";
erPatient[0].priority = 1;
erPatient[1].name = "Mary Smith";
erPatient[1].priority = 0;
erPatient[2].name = "Sam Smith";
erPatient[2].priority = 3;
for (int i = 0; i <= erPatient.GetUpperBound(0); i++)
{
erwait.Enqueue(erPatient[i]);
}
Console.WriteLine(erwait.Count);//值为3
nextPatient =(pqItem)erwait.Dequeue();
Console.WriteLine(erwait.Count);//值为0
Console.WriteLine(nextPatient.name);
Console.Read();
}
}
}
网友评论