【问题标题】:Trying to implement a priority queue with an ordered linked list尝试使用有序链表实现优先级队列
【发布时间】:2013-10-30 00:35:27
【问题描述】:

所以我要做的是使用有序链表实现一个优先级队列。我觉得我很接近,但我似乎无法解决插入函数中 while 语句中的错误。到目前为止,这是我所拥有的:

class OrderedLinkedListMaxPQ<Item> {

private class PQNode {
    Object data; 
    PQNode next;

    public PQNode(Object value) {
        data = value;
        next = null;
    }
}

PQNode head;

public void PriorityQueue() { 
    this.head = null; 
}

public boolean isEmpty() { return this.head == null; }

public void insert(Object item) {

   PQNode prev = null;
   PQNode current = this.head;
   while (current != null && current.data >= item.data) {
       prev = current;
       current = current.next;
   }

   PQNode temp = new PQNode(item);
   if (prev == null) {
       temp.next = this.head;
       this.head = temp;
   } else {
       temp.next = current;
       prev.next = temp;
   }   
}

public Object delete() {
   Object temp = this.head.data;
   this.head = this.head.next;
   return temp;
}

public static void main(String[] args) {
    OrderedLinkedListMaxPQ<Integer> pq = new OrderedLinkedListMaxPQ<Integer>();
    pq.insert(7);
    pq.insert(6);
    pq.insert(3);
    pq.insert(2);
    while (!pq.isEmpty())
        StdOut.println(pq.delete());
   }
}

【问题讨论】:

  • 在第一个 insert() 上,你没有得到一个 NullPointer 吗?
  • @iluxa 如果你的意思是因为 while 条件,它应该短路并且不会击中 current.data。
  • "使用有序链表实现优先级队列。"为什么? java.util.PriorityQueue 有问题吗?这是 O(log(N))。 你的是 O(N)。 不要这样做。

标签: java linked-list queue priority-queue


【解决方案1】:

current.data &gt;= item.data 毫无意义。 data 是一个对象引用,您无法比较它们。也许,如果 dat 值是 Comparable,您可以使用 compareTo(...) 方法。否则,您将需要编写自己的机制来比较它们。此外,item 作为 Object 传入,但您将其引用为 PNode ...这也是一个问题。

【讨论】:

  • 感谢您的帮助。我将如何在此类中实现 compareTo ?我应该制作一个单独的帮助方法来比较这两个值吗?抱歉,我对此有点迷茫。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 2017-02-08
  • 2014-01-19
相关资源
最近更新 更多