链表插入 [英] linkedlist insertion
本文介绍了链表插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试在2000个元素的列表上运行此代码时,谁能告诉我为什么我要用掉堆空间?
Can anyone tell me why Iam running off heap space when I try to run this code on a list of 2000 elements?
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);
}
}
推荐答案
这似乎可以解决您的方法:
This seems to fix your method:
while (j >= 0 && (portion.get(j).compareTo(value) >= 0)) {
portion.add(j, portion.remove(j));
您的代码不断添加元素,而不是移动它们.
Your code keeps adding elements instead of moving them.
这篇关于链表插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文