简体   繁体   English

如何有效地在一个列表中对两个双链表求和?

[英]How to sum two double linked lists in one list efficiently?

For example listA = [3,6,7,4] and listB = [2,3,1] and the output has to be listC=[5,9,8,6].例如 listA = [3,6,7,4] 和 listB = [2,3,1] 并且 output 必须是 listC=[5,9,8,6]。 This is what I have so far but it is not very efficient.到目前为止,这是我所拥有的,但效率不高。

`public void sum(doublelist aList) {`
for (int i = 0; i < size(); i++) {
     set(i, this.get(i) + other.get(i % other.size()));
}
}

As you said you are using linked lists, you could navigate from element to element:正如您所说,您正在使用链表,您可以从一个元素导航到另一个元素:

public void sum(DoubleList aList){
    DoubleNode cur=this.head;
    DoubleNode other=aList.head;
    while(cur!=null){
        cur.setValue(cur.getValue()+other.getValue());
        other=other.getNext();
        if(other==null){
            other=aList.head;
        }
        cur=cur.getNext();
    }
}

This code assumes that your DoubleList contains a head node attribute named head from the type DoubleNode and DoubleNode has the methods double getValue() / void setValue(double value) for accessing the value and DoubleNode getNext() for retrieving the next element.此代码假定您的DoubleList包含类型为DoubleNode的名为head的头节点属性,并且DoubleNode具有用于访问值的方法double getValue() / void setValue(double value)和用于检索下一个元素的DoubleNode getNext()方法。

This should be more efficient as you don't have to query the list every time ( O(n) instead of O(n^2) ).这应该更有效,因为您不必每次都查询列表( O(n)而不是O(n^2) )。

The answer is totally dependent of what kind of List you are using.答案完全取决于您使用的是哪种列表。

But anyway, the best complexity you can get is O(n), you will have to iterate at least one time over each element of the lists.但无论如何,您可以获得的最佳复杂度是 O(n),您将必须对列表的每个元素至少迭代一次。

The easiest is to use a ListIterator, that allow to set a value while iterating over the list.最简单的是使用 ListIterator,它允许在遍历列表时设置一个值。

    void sum(List<Integer> l1, List<Integer> l2) {
        final ListIterator<Integer> it1 = l1.listIterator();
        final Iterator<Integer> it2 = l2.iterator();
        
        while (it1.hasNext() && it2.hasNext()) {
            it1.set(it1.next() + it2.next());
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM