我觉得我把事情变得过于复杂了,因为我发现有很多边界情况。这是大学的作业,所以请仅给我提示,而不是我可以复制/粘贴的代码。 我正在尝试创建一个优先级队列,对包含字符的元素进行排序。它们应根据优先级值进行排列,如果优先级存在冲突,则应按字母顺序排列。我遇到的问题是插入元素。这是我目前拥有的代码:
public void insertItem(int priority, char content) {
boolean isSpecialCase = false;
PList current;
if (isEmpty()) {
high = new PList(priority, content, null, null);
low=high;
System.out.println(content + " has been added to an empty list");
isSpecialCase = true;
}
if (priority >= high.getPriority() && content >= high.getContent() && !isSpecialCase) {
PList newItem = new PList(priority, content, high, null);
high.setBehind(newItem);
high = newItem;
isSpecialCase = true;
System.out.println(content + " has been added to a non empty list - highest priority");
}
if (priority < low.getPriority() && !isSpecialCase) {
PList newItem = new PList(priority, content, null, low);
low.setNext(newItem);
low = newItem;
isSpecialCase = true;
System.out.println(content + " has been added to a non empty list - absolute lowest priority");
}
if (priority == low.getPriority() && content > low.getContent() && !isSpecialCase) {
PList newItem = new PList(priority, content, low, low.getBehind());
low.getBehind().setNext(newItem);
low.setBehind(newItem);
isSpecialCase = true;
System.out.println(content + " has been added to a non empty list - lowest priority-highest char");
}
if (priority == low.getPriority() && !isSpecialCase) {
if (content < low.getContent()) {
PList newItem = new PList(priority, content, null, low);
low.setNext(newItem);
low = newItem;
isSpecialCase = true;
System.out.println(content + " has been added to a non empty list -lowest priority");
}
}
current = high;
while (current.getNext() != null && !isSpecialCase) {
if (current.getPriority() >= priority) {
if (current.getContent() > content) {
PList newItem = new PList(priority, content, current.getNext(), current);
current.getNext().setBehind(newItem);
current.setNext(newItem);
break;
}
}
current = current.getNext();
}
}
它看起来很困惑并且有点重复,所以这就是为什么我认为我走错了路。 它适用于大多数情况,但例如当我运行时我得到一个 nullPointer:
PriQueue p = new PriQueue();
p.insertItem(5, 'a');
p.insertItem(5, 'a');
p.insertItem(4, 'x');
p.insertItem(4, 'a');
p.insertItem(4, 'x');
还有其他情况,它只是不将所有元素放入队列而不给出任何错误。
提前谢谢
最佳答案
我同意您使事情变得过于复杂,在没有给出完整解释的情况下,您应该考虑在您的 PList
项目上实现 Comparable
接口(interface)。然后,当您插入新项目时,您可以循环遍历列表,直到 listNode.compareTo(newNode) > 0
,这就是您插入它的位置。
关于java - 如何制作一个也考虑元素内容的优先级队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20317097/