如何使用排序链表实现优先级队列?
我想在 C# 中实现这个,我已经准备好了链接列表类,但是当我使用此排序方法对类进行排序时出现问题。如何给予元素优先级,以便优先级最高的元素首先出队。
public void Sort()
{
ListNode current=first;
int temp;
for (int i = 0; i < counter; i++)
{
while (current.Next != null)
{
if (current.Data > current.Next.Data)
{
temp = current.Data;
current.Data = current.Next.Data;
current.Next.Data = current.Data;
}
current = current.Next;
}
}
}
i want to implement this in c#, i have my linked list class ready, but problem occurs when i sort the class using this Sort method. How can I give priority to elements, so that the highest priority element dequeue first.
public void Sort()
{
ListNode current=first;
int temp;
for (int i = 0; i < counter; i++)
{
while (current.Next != null)
{
if (current.Data > current.Next.Data)
{
temp = current.Data;
current.Data = current.Next.Data;
current.Next.Data = current.Data;
}
current = current.Next;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
稍微分析一下你的代码:
这看起来就像冒泡排序的一笔,所以不要指望它能对所有内容进行排序。
它只会确保最大值成为最后元素。并且只有在修复交换部分之后:
To analyze your code a little:
This looks like 1 stroke of a bubble-sort, so don't expect it to sort everything.
It will only ensure that the largest value becomes the last element. And only after you fix the swap part:
我认为您不必像这样对列表进行排序,只需创建一个插入例程,在正确的位置插入任何新元素,您的列表将始终被排序。
平均GJ
I don't think you have to sort the list like this, just create an insert routine that inserts any new elements in the right spot and your list will always be sorted.
Rgds GJ