我必须编写一个复制函数,它复制链表的每个元素并返回一个链表,如果L = [2,3,4]则复制(L)= [2,2,3,3, 4,4]。我必须递归地这样做。我意识到下面不是正确的解决方案,但我感到困惑。 =(
public class MyList {
int value;
MyList next;
public static MyList duplicate(MyList L){
if(L.next == null){
L.next.value = L.value;
L.next.next = null;
} else {
MyList temp = L.next;
L.next.value = L.value;
L.next.next = temp;
duplicate(L.next);
}
return L;
}
}
答案 0 :(得分:0)
首先,检查L
是否不是空列表(null
)。如果它包含值,则返回一个重复两次该值的新列表,然后复制列表的其余部分。
通过赋予MyList
构造函数,这更具可读性。
public class MyList {
int value;
MyList next;
public MyList(int value, MyList next) {
this.value = value;
this.next = next;
}
public static MyList duplicate(MyList list) {
if (list == null) {
return null;
} else {
return new MyList(list.value,
new MyList(list.value,
duplicate(list.next)));
}
}
}
答案 1 :(得分:0)
您目前添加商品,然后在其上调用递归,结束于无休止地添加商品。
在向前处理时,您需要在后面递归,或者在向后处理时递归 。
让我们创建一个向后方向的版本。我们首先递归地走到列表的末尾,然后向后解析递归,每次在当前元素之后添加项。
public <E> void duplicateEntries(MyLinkedList<E> list) {
// Do nothing if list is empty
if (list.size() != 0) {
// Call the recursive method on the head node
duplicateEntriesHelper(list.head);
}
}
public <E> void duplicateEntriesHelper(Node<E> node) {
// Walk to the end of the list
if (node.next != null) {
duplicateEntriesHelper(node.next);
}
// Resolve recursion, duplicate current
// entry by inserting it after the current element
Node<E> duplicatedEntry = new Node<>();
duplicatedEntry.data = node.data;
// Insert element after current node
duplicatedEntry.next = node.next;
node.next = duplicatedEntry;
}
我使用的类应该类似于:
public class MyLinkedList<E> {
public Node<E> head = null;
@Override
public String toString() {
// Build something like "MyLinkedList[2, 3, 4]"
StringBuilder sb = new StringBuilder();
sb.append("MyLinkedList[");
StringJoiner sj = new StringJoiner(",");
Node<E> node = head;
while (node != null) {
sj.add(node);
node = node.next;
}
sb.append(sj);
sb.append("]");
return sb.toString();
}
}
public class Node<E> {
public Node next = null;
public E data = null;
@Override
public String toString() {
return E;
}
}
以下是演示:
public static void main(String[] args) {
// Setup the list
MyLinkedList<Integer> list = new MyLinkedList<>();
Node<Integer> first = new Node<>();
first.data = 2;
Node<Integer> second = new Node<>();
second.data = 3;
Node<Integer> third = new Node<>();
third.data = 4;
list.head = data;
first.next = second;
second.next = third;
// Demonstrate the method
System.out.println("Before: " + list);
duplicateEntries(list);
System.out.println("After: " + list);
}
当然,您可以为它们添加其他方法和功能。例如,使用一些构造函数或 getter / setter 方法。