我正在尝试将一个列表复制到另一个列表中,我有其他方法,例如删除,当我测试它们时,复制方法似乎正在编辑原始列表。
复制方法如下所示。
public ImmutableList<T> copy(ImmutableLinkedList<T> list) {
Node n = list.head;
ImmutableLinkedList<T> listcopy = new ImmutableLinkedList<T>();
listcopy.head = list.head;
copynode(list.head.next, listcopy.head.next);
return listcopy;
}
private Node copynode(Node list, Node listcopy){
if(list == null){
return listcopy;
} else{
listcopy.data = list.data;
listcopy.next = list.next;
return copynode(list.next, listcopy.next);
}
}
将代码更改为此,但仍然无法正常工作
public void copy(ImmutableListImplement<T> list) {
ImmutableListImplement<T> listcopy = new ImmutableListImplement<T>();
this.head = copynode(list.head, listcopy.head);
}
private Node copynode(Node list, Node listcopy){
if(list == null){
return listcopy;
} else{
listcopy = new Node();
listcopy.data = list.data;
listcopy.next = list.next;
copynode(list.next, listcopy.next);
}
return listcopy;
}