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;
}
If you are trying to concatenate multiple immutable lists you can use the static inner class ImmutableList.Builder.
Output: [1,2,3,4,5,6]