提问人:Papu Gomez 提问时间:3/2/2022 最后编辑:Papu Gomez 更新时间:3/2/2022 访问量:678
如何使用两个图像中附加的自定义接口实现优先级队列?
How to implement priority queue using Custom interfaces as attached in both the images?
问:
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyQueue
{
public class PriorityQueue<T> where T : IEquatable<T>
{
private IDictionary<int, IList<T>> elements;
public PriorityQueue()
{
elements = new SortedDictionary<int, IList<T>>();
}
public PriorityQueue(IDictionary<int, IList<T>> elements) : this()
{
}
public int Count()
{
return elements.Count;
}
public bool Contains(T item)
{
bool res = false;
foreach (KeyValuePair<int, IList<T>> pair in elements)
{
enter image description here
if (pair.Value[0].Equals(item))
{
Console.Write($"{item} Found --> {pair.Key} {pair.Value[0]}");
res = true;
}
if (res == true)
{
return res;
}
}
return res;
}
public T Dequeue()
{
IList<T> list = elements[elements.Keys.First()];
int priority = elements.Keys.First();
T highestPriority = list.First();
list.Remove(highestPriority);
if (list.Count == 0)
{
elements.Remove(priority);
}
return highestPriority;
}
public void Enqueue(int priority, T item)
{
IList<T> items;
if (!elements.ContainsKey(priority))
elements.Add(priority, new List<T>());
items = elements[priority];
items.Add(item);
}
public T Peek()
{
IList<T> priorityList = elements[elements.Keys.First()];
return priorityList[0];
}
public int getHighestPriority()
{
int Firstkey = elements.Take(1).Select(d => d.Key).First();
return Firstkey;
}
}
class Program
{
static void Main(string[] args)
{
PriorityQueue<string> priorityQueue = new PriorityQueue<string>();
priorityQueue.Enqueue(3, "Iooawi");
priorityQueue.Enqueue(1, "Zuika");
priorityQueue.Enqueue(2, "Aki");
priorityQueue.Enqueue(5, "Iak");
Console.WriteLine($"Top item: -> { priorityQueue.Peek()}");
Console.WriteLine($"Removed item--> {priorityQueue.Dequeue()}");
Console.WriteLine($"Top item: -> { priorityQueue.Peek()}");
Console.WriteLine($"Items present in this queue {priorityQueue.Count()}");
Console.WriteLine($" ---> { priorityQueue.Contains("Iak")}");
Console.WriteLine($"{priorityQueue.getHighestPriority()}");
}
}
}
如何使用图中给出的自定义接口实现以下实现,上面是我尝试过的代码,以及如何将字段添加到自定义接口。 我尝试在上面的实现中使用 Iequatable,但在自定义界面 Ipriority 中,它不允许我设置字段 int priority? 实现接口的方法有哪些?另外,如果我将其设置为私有,如何访问setHighestPriority方法?
答: 暂无答案
评论