【发布时间】:2013-12-01 20:49:30
【问题描述】:
我觉得我把事情复杂化了,因为我发现有很多边界情况。这是大学的作业,所以请只给我提示,而不是我可以复制/粘贴的代码。 我正在尝试创建一个优先级队列来对包含字符的元素进行排序。它们应该根据优先级值排列,如果优先级有冲突,则按字母顺序排列。我遇到的问题是插入元素。这是我目前拥有的代码:
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');
还有其他一些情况,它只是没有将所有元素放入队列而不给出任何错误。
提前谢谢你
【问题讨论】:
-
添加堆栈跟踪会很有用。
-
你熟悉Heap吗?
-
通过堆,我是否会通过以父级优先级来实现它,而子级将按字符排列?
标签: java data-structures priority-queue