繁体   English   中英

基于链接列表从优先级队列中删除项目

[英]Removing an Item From a Priority Queue Based on a Linked List

我试图在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
    }
}

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

或者考虑使用双向链表,以便您对下一个和上一个节点都有引用,或者使用Node<E> nodeReferencingHighestPriority; 并在循环中跟踪它:

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

        previous = current;
        current = current.next;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM