java - 链表排序方法在递归和比较列表中的元素时给出 StackOverFlow 错误

标签 java sorting recursion linked-list

我从头开始创建了链表,并添加了诸如addremovesetsize等方法。我还添加了一个简单的静态递归sort方法,该方法接受链表引用作为参数,以便可以在名为sort(linkedList);的Main类中使用它。它返回一个排序的链表。

程序抛出 Exception in thread "main" java.lang.StackOverflowError ,在行,if (biggest.compareTo(nextNode.value) < 0) biggest = nextNode.value;return sort(list); 。我希望排序方法按字母顺序对列表进行排序(我的链接列表由字符串元素组成)。

这是代码中的方法:

 /**
     * The sort method sorts the list in alphabetical order
     * @param list list to be sorted
     * @return sorted linked list
     */
static DD_RecursiveLinkedList sort(DD_RecursiveLinkedList list) {
        DD_Node nextNode = head.next;
        String biggest = head.value, smallest = tail.value; //by default biggest is the head, and smallest is the tail
        if (isEmpty()) return null; //if list is empty, return null
        do { //find the biggest and smallest value in the list
            if (biggest.compareTo(nextNode.value) < 0) biggest = nextNode.value; //if nextNode is bigger than the biggest, biggest is nextNode
            if (smallest.compareTo(nextNode.value) > 0) smallest = nextNode.value; //if nextNode is smaller than the smallest, smallest is nextNode
            nextNode = nextNode.next; //update nextNode
        } while (nextNode!=null); //loop until nextNode is null

        set(0, biggest); set(size()-1, smallest); //set biggest as the head of the list, and smallest as the tail
//        remove(biggest);//remove the biggest (head) from the list
//        remove(smallest); //remove the smallest (tail) from the list
//        list.add(0, biggest); //add the biggest to the sorted list as head element
//        list.add(size()-1, smallest); //add the smallest to the sorted list as tail element
        return sort(list); //sort the order of sorted list recursively
    }
<小时/>

我已经注释掉了addremove行,因为它们包含在错误中,所以而不是 addremove方法,我用过set方法,用指定元素替换指定索引处的元素。

最佳答案

这里的问题是,sort(list)方法将被无限次调用,导致java堆栈溢出,并且无法在堆栈中进一步存储任何变量。

return sort(list);

1.由于没有限制递归应该在什么条件下进行。停止。它将继续调用sort()。 - 这会导致 stackOverflow 错误

2.由于remove()语句被注释了。列表大小根本没有改变。因此它也不会在 isEmpty 检查处停止。另外:因为无论你列出什么,它最终都会返回 null。

关于java - 链表排序方法在递归和比较列表中的元素时给出 StackOverFlow 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55928327/

相关文章:

java - 使用maven和intellij idea编译java app的区别

java - 扩展 AlertDialog 还有什么问题 为什么对话框中的 EditText 中没有自动 IME

java - Spring 可分页排序与 mongoOperations 一起工作不正确。排序顺序不正确

java - Quicksort:wikipedia-implementation 不工作

recursion - 部分应用的嵌套递归

java - @OneToMany 中不必要的更新

java - bin的java.exe和JRE的 'java.exe'的区别

c++ - 划分快速排序逻辑错误

C++ - 解决数独游戏

postgresql - 递归嵌套 jsonb 结构的全文索引