优先链接队列添加方法帮助

时间:2018-10-07 21:42:41

标签: java nodes priority-queue

我正在尝试使用链接的节点实现优先级队列,除了add方法之外,我所有的方法都可以正常工作。 add方法的目的是以正确的顺序将可比较的对象添加到队列中。队列的顺序如下:最高优先级的节点是firstNode。对于我在尝试中做错的任何帮助,将不胜感激。

public void add(T newEntry) {

   if(newEntry == null) {
       return;
   }

   if(isEmpty()) { 
      firstNode = new Node(newEntry);
   } else {
       Node currentNode = firstNode;
       if(newEntry.compareTo(firstNode.data)<0) {
           firstNode = new Node(newEntry, firstNode);
           length++;
           return;
       } else {
           while(currentNode.getNextNode() != null && newEntry.compareTo(currentNode.next.data) > 0) {
                  currentNode = currentNode.next;
                  currentNode.setNextNode(new Node(newEntry, currentNode.getNextNode()));
           }
       }
   }
   length++;
   return;     
} 

1 个答案:

答案 0 :(得分:0)

您至少有两个问题,我已在代码注释中指出:

public void add(T newEntry) {

   if(newEntry == null) {
       return;
   }

   if(isEmpty()) { 
      firstNode = new Node(newEntry);
   } else {
       Node currentNode = firstNode;
       if(newEntry.compareTo(firstNode.data)<0) {
// Here you're assigning a new value to firstNode, but not linking to the old
// firstNode. So you're losing the entire list.
           firstNode = new Node(newEntry, firstNode);
           length++;
           return;
       } else {
           while(currentNode.getNextNode() != null && newEntry.compareTo(currentNode.next.data) > 0) {
                  currentNode = currentNode.next;
// Here you're adding multiple new nodes to the list.
                  currentNode.setNextNode(new Node(newEntry, currentNode.getNextNode()));
           }
       }
   }
   length++;
   return;     
}

您可以轻松地简化它:

public void add(T newEntry) {

   if(newEntry == null) {
       return;
   }
   Node newNode = new Node(newEntry);

   if(isEmpty()) { 
      firstNode = newNode;
   } else if (newNode.data < firstNode.data) {
      // make newNode point to the firstNode,
      // and then re-assign firstNode
      newNode.setNextNode(firstNode);
      firstNode = newNode;
   } else {
       Node currentNode = firstNode;
       Node nextNode = currentNode.getNextNode;
       while (nextNode != null && nextNode.data > newNode.data) {
           currentNode = nextNode;
           nextNode = currentNode.getNextNode;
       }
       // insert newNode between currentNode and nextNode
       newNode.setNextNode(nextNode);
       currentNode.setNextNode = newNode;
   }
   length++;
   return;     
}