java - 两个单链表的非破坏性递归相交

标签 java recursion intersection

我想获取两个单向链表(此函数从一个内部调用)并创建第三个单向链表,其中包含两者之间的所有交集。所以如果 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;
    }
}

最佳答案

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 只包含两个列表中的元素,而列表本身保持不变。

关于java - 两个单链表的非破坏性递归相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18897434/

相关文章:

c++ - 设置射线(原点,方向)和三角形交点(无glm)

Java 8 类型推断导致在调用时忽略泛型类型

java - 从 JSON 中提取字节数组

recursion - Ocaml - 迭代到递归

java - 递归对象设置java

java - 检查两个 Path2D 之间的交集

geometry - 如何修复自相交的多边形?

Java 图标不会显示两次

java - 打印序列中的下一个 ASCII 字符

java - 以递归方式检查初学者(不是作业,是我学习的一部分)