2

我想获取两个单链表(从一个内调用此函数)并创建第三个单链表,其中包含两者之间的所有交集。因此,如果 p=[0,1,2,3] 和 q=[1,3,7,9] 则 out=[1,3],同时保持旧列表不变。

如您所见,我需要在两个地方声明“out”。但是,如果我再次调用该函数来点击声明,它自然会擦除我之前写给它的内容。我真的不知道如何避免它。

可以使用http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html生成单链表。首先是我的标题。

public List intersection(List l) {
    if(first.data == l.first.data) {
        List lTail = new List(l.first.next);
        List tail = new List(first.next);

        List out = new List(new Node(first.data, null)); //Bad idea #1
        // System.out.println(out);

        return tail.intersection(lTail);
    } else if (first.data > l.first.data && l.first.next != null) {
        List lTail = new List(l.first.next);
        return intersection(lTail);

    } else if (first.data < l.first.data && first.next != null) {
        List tail = new List(first.next);
        return tail.intersection(l);
    } else { //When both lists are at the end position
        List out = new List(new Node(0, null)); // Bad idea #2
        return out;
    }
}
4

1 回答 1

0
List<T> p = new LinkedList<T>();
p.add...
...
List<T> q = new LinkedList<T>();
q.add...
...
List<T> intersection = new LinkedList<T>(p);
intersection.retainAll(q);

现在intersection只包含两个列表中的元素,而列表本身保持不变。

于 2013-09-19T14:31:27.003 回答