I am trying to copy a list into another list, I have other methods such as remove and when I am testing them the copy method seems to be editing the original list.
The copy method is shown hereunder.
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);
}
}
Altered the code to this, but still not working
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;
}
listcopy.headis a reference to the original list's head element. It is not a copy at all. Then you pass this into thecopynodemethod as parameterlistcopy, andcopynodemesses with the entries therein.Effectively,
list.head.next==listcopy.head.next(as in, both point to the exact same Node object) in yourcopynode()call on line 6. That's the problem here.