简体   繁体   中英

JAVA Immutablilty, Copying a Linked List

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 (ie 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;


}

I'm not much for Java, but can't you just do

clonedList.add(n.data)

in your while loop to create a deep copy?

If you don't need a deep copy, you should just be able to set the head of the cloned list to that of the original, eg:

LinkedList<T> clonedList = new LinkedList<>();
clonedList.head = toCopy.head;

Otherwise, construct a new Node on each loop iteration and add it to the cloned list. It sounds to me like you have your own LinkedList implementation without an add method, so either write one or replace the method call in the example.

Node<T> n = toCopy.head;
LinkedList<T> clonedList = new LinkedList<>();

while(n != null) {
    Node<T> nClone = new Node<>(toCopy.data);
    clonedList.add(nClone);
    n = n.next;
}

Also, this method should probably either be a constructor or a static method. It doesn't make sense to require an instance for a method that doesn't modify the list's state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM