微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用双向链表的优先队列

如何解决使用双向链表的优先队列

我正在尝试使用双向链表实现一个优先级队列,但我坚持插入节点。

任务是: 一种向列表中插入新元素的方法。要插入元素,您应该计算列表中第一个和最后一个元素的平均值(如果列表包含元素)。如果新元素优先级的数值小于此平均值,则应从列表的开头插入元素,否则从列表的末尾插入以节省时间。

    public class Node<Item> { //node class with priority,value and pointers to next and prev
    Item item;
    int  priority;
    Node next;
    Node prev;
}

public <Item> void add(Item value,int priority){ //fixa asap
    Node tmp = new Node();
    int currentpriority = sentinel.next.priority + sentinel.prev.priority / 2;

    if (sentinel.next == this.sentinel ) {  //if its empty add after sentinel
        sentinel.next.prev = tmp;
        tmp.next = null;
        tmp.prev = sentinel;
        sentinel.next = tmp;
        tmp.item = value;
        tmp.priority = priority;
    }

        else if (priority <= sentinel.next.priority){  //if the first element is larger than the new element replace it with the new one at the front
        sentinel.next.prev = tmp;
        tmp.next = sentinel.next;
        tmp.prev = sentinel;
        sentinel.next = tmp;
        tmp.item = value;
        tmp.priority = priority;
    }
    else if (priority >= sentinel.prev.priority){  //if the last element is smaller than the new element replace it with the new one at the front
        sentinel.prev.next = tmp;
        tmp.prev = sentinel.prev;
        tmp.next = null;
        sentinel.prev = tmp;
        tmp.item = value;
        tmp.priority = priority;
    }

        else if(priority <= currentpriority ) { // if true add FROM the front
            Node start = sentinel.next;
            while (priority > start.priority)
            start = start.next;
             System.out.println("Test from the front");
            tmp.next = start;
            tmp.prev = start.prev;
            start.prev = tmp;
            tmp.item = value;
            tmp.priority = priority;

    }

如果我运行它并插入 2 个节点,即优先级为 1 的 1 和优先级为 3 的节点,我得到 1 3

现在我想插入优先级为 2 的 2 但它没有出现在列表中,它仍然 1 3

我做错了什么? 谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。