gpt4 book ai didi

java - 链表插入

转载 作者:行者123 更新时间:2023-12-01 14:46:45 25 4
gpt4 key购买 nike

谁能告诉我,为什么当我尝试在 2000 个元素的列表上运行此代码时,我会耗尽堆空间?

public static <T extends Comparable <? super T>> void insertionSort2(List<T> portion){
int i = 0;
int j = 0;
T value;
//List <T> sorted = new LinkedList<T>();

// goes through the list
for (i = 1; i < portion.size(); i++) {

// takes each value of the list
value = (T) portion.remove(i);

// the index j takes the value of I and checks the rest of the array
// from the point i
j = i - 1;

while (j >= 0 && (portion.get(j).compareTo(value) >= 0)) {
portion.add(j + 1, portion.get(j));

j--;

}
// put the value in the correct location.
portion.add(j + 1, value);
}
}

最佳答案

这似乎可以修复您的方法:

while (j >= 0 && (portion.get(j).compareTo(value) >= 0)) {
portion.add(j, portion.remove(j));

您的代码不断添加元素而不是移动它们。

关于java - 链表插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15375690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com