下面的代码构造了 2 个链表,并将它们都传递给构造了第三个合并链表。然而,一旦合并,l1 和 l2(最初构造的)链表就发生了变化。在这段代码中, l1 和 l2 应该在哪里设置为 null ?
编辑:将其设置为 null 的原因是我们不希望客户端将来使用修改后的 l1 或 l2。我们希望有一个明确的合同,一旦合并,我们就会有一个全新的引用,并且以前的引用无效,这样就不会有人认为他们在构建时是链表而使用它们。
public class MergeLinkedList {
Node first;
Node last;
public void add (int val) {
final Node l = last;
final Node newNode = new Node(val, null);
last = newNode;
if (first == null) {
first = newNode;
} else {
l.next = newNode;
}
}
public void displayList() {
Node tempFirst = first;
while (tempFirst != null) {
System.out.print(tempFirst.item + " ");
tempFirst = tempFirst.next;
}
}
private static class Node {
int item;
Node next;
Node(int element, Node next) {
this.item = element;
this.next = next;
}
}
private Node mergeLinkedListRecursive(Node list1, Node list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
if (list1.item < list2.item) {
list1.next = mergeLinkedListRecursive(list1.next, list2);
return list1;
} else {
list2.next = mergeLinkedListRecursive(list1, list2.next);
return list2;
}
}
public void mergeLinkedListRecursion(MergeLinkedList list1, MergeLinkedList list2) {
first = mergeLinkedListRecursive(list1.first, list2.first);
}
public static void main(String[] args) {
int[] a1 = {1, 3, 5};
int[] a2 = {2, 4};
MergeLinkedList l1 = new MergeLinkedList();
for (int val : a1 ) {
l1.add(val);
}
MergeLinkedList l2 = new MergeLinkedList();
for (int val : a2) {
l2.add(val);
}
MergeLinkedList l3 = new MergeLinkedList();
l3.mergeLinkedListRecursion(l1, l2);
l3.displayList();
}
}