将一系列列表转换为子列表并将它们存储在类型为 linkedlist 的列表中

Convert a range of lists to sub list and store them in an list of type linkedlist

我已经有一个包含值的整数类型列表,如果一个范围内的元素之和满足特定值,我想从索引零开始顺序测试,然后将此范围复制到列表中并将其存储在列表中的链表。然后再次按顺序测试,但现在从前一个范围的下一个索引开始,所以如果前一个范围是索引 0 到索引 9,则从索引 10 开始,重复该过程直到最后一个索引。

List<Integer> arrayB = new LinkedList<Integer>(); //this is the array with values in it

List<LinkedList> p = new LinkedList<LinkedList>();// this is the array of arrays  

List<Integer> arrayA = new LinkedList<Integer>();// this is the range or the sub list of arrayB

public void function(int n)// suppose that n = 6 and arrayB have these value {1,2,3,1,1,1,1,2}
{
    int count = 0;

    for (int w : arrayB)
    {
        count = w + count;
        arrayA.add(w);
        if(count == n)
        {
            count = 0;
            p.add((LinkedList) arrayA);
            arrayA.clear();
        }
    }
}

但是,当我调用 arrayA 中的 clear 方法时,这段代码失败了,所以无论使用何种数据结构,是否有任何替代方法可以使用这种逻辑编写代码?

每次将子列表添加到 p 时,您都在使用相同的列表引用 arrayA,p 中的每个列表元素都指向相同的 arrayA。所以当你调用 arrayA.clear();您清除 p.

中的所有列表元素

要更正此问题,您需要在将子列表添加到 arrayA 时创建一个新的列表对象:

public static void function(int n)// suppose that n = 6 and arrayB have these value {1,2,3,1,1,1,1,2}
{
    int count = 0;

    LinkedList<Integer> subList = new LinkedList<>();
    for (int w : arrayB) {
        count = w + count;
        subList.add(w);
        if (count == n) {
            count = 0;
            p.add((LinkedList) subList); // p is adding a new list reference every time
            subList = new LinkedList<>(); // create a new list object, subList points to a new list object
        }
    }
}

我对问题的理解如下: 存在一个数组,您希望从中提取特定范围的值,前提是它们满足某些条件。在这种情况下,标准是范围评估为某个总和。完成后,您希望重复该过程,直到用完原始数据结构中的所有值。 我将假设您的原始数据结构是一个整数数组,并且您生成的数据结构是一个整数数组的链表。

一种方法可能是保留一个全局计数器来跟踪原始数组的当前索引,例如以下内容:

int[] originalArray = {//list of numbers separated by commas};
LinkedList<Integer[]> resultingList = new LinkedList<>();
int currentIndex = 0;

public static void function(int totalSum) {
    int currentSum = 0;
    int initialIndex = currentIndex;
    while((currentSum != totalSum) && (currentIndex < (originalArray.length - 1))) {
        if(currentSum + initialArray[currentIndex] <= totalSum) {
            currentSum += initialArray[currentIndex];
            currentIndex++;
        } 
        else {
            break;
        }
    }
    if(currentSum = totalSum) {
        int[] arrayToAdd = new int[currentIndex - initialIndex - 1];
        for(int i = 0; i < currentIndex - initialIndex; i++) {
            arrayToAdd[i] = originalArray[initialIndex + i];
        }
        resultingList.add(arrayToAdd);
    }
}

问题是,当您将链表添加到最终存储 p 中时,您假设列表的元素都放在那里。只有一个指针被引用,所以当你在下一行清除它时,所有元素都消失了。

p.add((LinkedList) arrayA);
arrayA.clear();

一个技巧是将 arrayA 的作用域移动到函数内部。这是因为它是临时的,只是一个子列表,所以它不应该在实例级别。它可以通过做 a

来重用
arrayA = new LinkedList<Integer>();

这样做时,您并没有丢失旧列表,因为 p 保留了对它的引用。

另一个提示是用有意义的名称命名您的列表。

originalIntList、groupedIntList、singleGroupIntList 帮助 reader 弄清楚他们可以做什么,而不是评论说明 Java 对象的明显方面。