我觉得我过于复杂化,因为我发现有太多的边界情况。这是大学的作业,所以请只给我提示,而不是我可以复制/粘贴的代码。 我正在尝试创建一个优先级队列来命令包含字符的元素。应根据优先级值排列它们,如果优先级存在冲突,则按字母顺序排列。我遇到的问题是插入元素。这是我目前的代码:
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');
还有一些情况,它不会在没有任何错误的情况下将所有元素放入队列中。
提前谢谢
答案 0 :(得分:0)
我同意你过度复杂化,但没有给出完整的解释,你应该考虑在你的Comparable
项目上实施PList
界面。然后,当您插入新项目时,您可以遍历列表,直到listNode.compareTo(newNode) > 0
,这就是您插入的位置。