I am tasked with creating a Linked List class in Java that MUST be immutable. This has been accomplished exactly the same as on here:
https://www.geeksforgeeks.org/linked-list-set-1-introduction/
Among other methods, I need an addToList method that adds a value or multiple values to the tail of the Linked List. Since the Linked List is immutable, adding to it should create a copy of the Linked List (i.e. a new LinkedList object with the same contents) and only add the desired values to the newly created copy.
The copy function is where I need help. Below is the copyList function, partially completed. I am traversing each Node in the LinkedList and printing out the data successfully. Now I need to assign that data to the corresponding element in the clonedList (the new copy). Please see the image below.
public LinkedList<T> copyList(LinkedList<T> toCopy) {
Node n = toCopy.head;
LinkedList clonedList = new LinkedList<T>();
while(n != null) {
System.out.println("Copying: " + n.data);
/*code here(?) to assign elements to clonedList,
but how?
*/
n = n.next;
}
return clonedList;
}