【问题标题】:Removing an Item From a Priority Queue Based on a Linked List基于链表从优先级队列中删除项目
【发布时间】:2012-04-12 05:13:35
【问题描述】:

我正在尝试在 Java 中创建一个通过链接列表实现的 PriorityQueue 类。在队列中,具有不同优先级的对象将不按特定顺序添加到列表的末尾,因此添加一个元素将是 O(1),而删除具有最高优先级的元素将是 O(n)。但是,我很难编写 remove 方法。我在我的链接列表类中创建了一个“removeHighestPriorityNode”方法,但我被卡住了。这是我迄今为止所拥有的:

public void removeHighestPriorityNode()
{
    if(head == null)                                
    {
        throw new NoSuchElementException();
    }
    else if (head.next != null)
    {
        Node<E> previous = head;
        Node<E> current = head.next;
        Node<E> highestPriority = head;

        while(current != null)
        {
            if (current.priority > previous.priority)
            {
                highestPriority = current;
            }

            previous = current;
            current = current.next;
        }
    }
    else
    {
        clear(); //Clears the list
    }
}

找到具有最高优先级的节点是没有问题的,但是找到一种方法将指针(下一个)从具有最高优先级的节点之前的节点切换到之后的节点是我遇到的麻烦。另外,这是我第一次在这个网站上发帖,所以如果我有任何含糊不清的地方,请告诉我。任何帮助将不胜感激!谢谢。

【问题讨论】:

    标签: java linked-list priority-queue


    【解决方案1】:

    或者考虑使用双向链表,这样您就可以同时引用下一个和上一个节点,或者使用Node&lt;E&gt; nodeReferencingHighestPriority; 并在循环中跟踪它:

        while(current != null)
        {
            if (current.priority > previous.priority)
            {
                nodeReferencingHighestPriority = previous;
                highestPriority = current;
            }
    
            previous = current;
            current = current.next;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 2012-02-24
      • 2019-03-19
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      相关资源
      最近更新 更多