【发布时间】:2020-02-25 02:32:26
【问题描述】:
我正在尝试对一个自我实现的双向链表进行排序,但它似乎在无休止地迭代,我不确定我做错了什么。任何帮助将不胜感激。
public void sortLine() {
Module current = this.getLeftMostModule();
Module next = this.getLeftMostModule().getRight();
while(next != this.getRightMostModule()) {
while(next != null) {
if(current.getName().compareToIgnoreCase(next.getName()) > 0) {
swap(current, next);
}
next = next.getRight();
}
current = current.getRight();
}
}
public void swap(Module current, Module next) {
boolean isLeft = false;
boolean isRight = false;
if(current.isLeftMostModule()) {
isLeft = true;
}
if(next.isRightMostModule()) {
isRight = true;
}
Module temp = current;
current = next;
next = temp;
if(isLeft) {
next.setLeftMostModule();
current.setNonMostModule();
}
else if(isRight) {
next.setNonMostModule();
current.setRightMostModule();
}
}
我调用了一个交换函数,我也包括在内。谢谢你。我不允许添加 setName 方法,也无法访问除 getName 之外的名称字段。但是,我可以向此类添加辅助方法。
编辑——更新了代码,但它仍然无法正常工作。在 compareToIgnoreCase 上获取 NPE 并没有得到我想要的结果。
【问题讨论】:
-
交换“值”而不是“下一个”/“上一个”链接不是更容易吗?
temp = current.getName(); current.setName(next.getName()); next.setName(temp);你就完成了。 -
遗憾的是我不允许创建方法 setName() 并且名称字段是私有的。
标签: java bubble-sort doubly-linked-list