简体   繁体   English

两个单链表的无损递归相交

[英]Non-destructive recursive intersect of two singly linked lists

I want to take two singly linked lists (this function is called from within one) and create a third singly linked list that contains all intersections between the two. 我想获取两个单链列表(此函数从一个内部调用)并创建第三个单链列表,其中包含两者之间的所有交集。 So if p=[0,1,2,3] and q=[1,3,7,9] then out=[1,3], while leaving the old lists intact. 因此,如果p = [0,1,2,3]和q = [1,3,7,9],则out = [1,3],而完整保留旧列表。

As you can see I need to declare "out" in two places. 如您所见,我需要在两个地方声明“ out”。 But if I hit the declaration by calling the function again, it naturally wipes what I previously wrote to it. 但是,如果我再次调用该函数来达到该声明,那么它自然会抹去我之前写给它的内容。 I really can't figure out how to avoid it. 我真的不知道该如何避免。

Singly linked lists can be generated with http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html . 可以使用http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html生成单链列表。 first is my header. 首先是我的标题。

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;
    }
}
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);

Now intersection contains only elements, which are in both lists, while lists theirselves remain untouched. 现在, intersection仅包含两个列表中的元素,而列表自身保持不变。

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

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