java - 单链表冒泡排序

标签 java linked-list bubble-sort singly-linked-list

我已经在我的代码中实现了单链表,并且我必须对列表进行排序。 但我的代码不起作用,它陷入了无限循环。我必须根据节点的 id 按升序比较节点。

我不能使用数组。 这是我的 SLL 节点实现。

  class SLLNode implements Comparable<SLLNode> {
    protected int id;
    protected int plata;
    protected SLLNode succ;

    public SLLNode(int id,int plata, SLLNode succ) {
        this.id = id;
        this.plata=plata;
        this.succ = succ;
    }

    @Override
    public int compareTo(SLLNode o) {
        return o.id - this.id;
    }
}

public static void sort(SLL lista){
    SLLNode current;
    boolean check = true;
    while(check) {
        current = lista.getFirst();
        check = false;

        while(current.succ != null)
        {
            if(current.compareTo(current.succ) > 0)
            {
                SLLNode temp = current;
                current=current.succ;
                current.succ=temp;
                check = true;
            }
            current = current.succ;
        }
    }
}

最佳答案

您的问题在这里:

            // Take a copy of current.
            SLLNode temp = current;
            // Step to next.
            current=current.succ;
            // Point temp (old current) to new next <----- Added this.
            temp.succ = current.succ;
            // Point next's successor to current.
            current.succ=temp;
            // Remember to check again.
            check = true;

您缺少更改 temp.succ。您需要在适当的位置将其设置为 current.succ

总之 - 要交换两个节点 a 和 b,您需要执行以下操作:

  • 设置 a.succ = b.succ <--- 你错过了这个。
  • 设置 b.succ = a

如果没有链接列表的示例实现,我无法测试它。

关于java - 单链表冒泡排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30670004/

相关文章:

c++ - 实现递归冒泡排序时遇到栈溢出

C 冒泡排序最大值变为0

java - 如何正确获取数字序列中的最大和最小数字?

java - 如何在 WAR 文件之间在 JSF 页面中导航?

c - 如何将第一个符号移到最后?

c - 删除链表的第一个节点

python - Pypy(Python)优化

java - 如何在 Java 中使用 for 循环从类创建新对象?

java - 然后,Object.toString(),编码为UTF-8

c++ - Try/Catch & Throw 无法正常工作