【问题标题】:Sorting A Doubly Linked List with Bubble Sort and a Swap Method使用冒泡排序和交换方法对双向链表进行排序
【发布时间】: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


【解决方案1】:

外部 for 循环中的 i 计数器从不递增。

【讨论】:

  • 我更新了代码,做了一些更改,但仍然无法正常工作。
猜你喜欢
  • 2014-02-04
  • 2022-01-09
  • 1970-01-01
  • 2017-09-27
  • 2011-04-13
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
相关资源
最近更新 更多