递归复制链表(Java)
一个漫长的夜晚结束后,我在递归复制链表时遇到了麻烦,我可以用一个简单的迭代方法来实现,但是当我尝试用递归设置它时,我遇到了堆栈溢出错误。然而,这在概念上对我来说是有意义的。谁能把我引向正确的方向?这就是我到目前为止所做的:
public LinkedList<E> createCopyRecursive(Node<E> aNode) {
LinkedList<E> copyList = new LinkedList<E>();
copyList.myStart = myStart;
if (copyList.size() == 0) {
aNode = myStart.getLink();
}
if (aNode.getLink() == null) {
return copyList;
}
else {
copyList.add(aNode.getValue());
return createCopyRecursive(aNode.getLink());
}
}
# 1 楼答案
您可以只担心头节点,而不是传递整个linkedlist对象
调用递归方法
copy()
递归方法copy,接受head节点并返回复制的head节点
# 2 楼答案
如果您想使用递归方法复制链接列表,我认为您应该首先在另一个调用createCopyRecursive()的方法中初始化copyList
# 3 楼答案
我认为可以这么简单:
首先创建一个空的新链表,其中将包含副本,然后逐节点递归地将副本复制到其中。您也不能像这样将累加器传递给它:
但这将颠倒列表中节点的顺序
下面是一个使用递归复制和递归反转的完整工作示例:
# 4 楼答案
每次递归到该方法时,都会创建一个新的LinkedList
我怀疑您希望在方法之外实例化它,每次通过时传入并添加它