简体   繁体   English

JAVA 不变性,复制链表

[英]JAVA Immutablilty, Copying a Linked List

I am tasked with creating a Linked List class in Java that MUST be immutable.我的任务是在 Java 中创建一个必须是不可变的链表类。 This has been accomplished exactly the same as on here:这与此处完全相同:

https://www.geeksforgeeks.org/linked-list-set-1-introduction/ 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.在其他方法中,我需要一个addToList方法,该方法将一个或多个值添加到链表的尾部。 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.由于链表是不可变的,添加到链表应该创建链表的副本(即具有相同内容的新 LinkedList 对象),并且只将所需的值添加到新创建的副本中。

The copy function is where I need help.复制功能是我需要帮助的地方。 Below is the copyList function, partially completed.下面是copyList函数,部分完成。 I am traversing each Node in the LinkedList and printing out the data successfully.我正在遍历 LinkedList 中的每个节点并成功打印出数据 Now I need to assign that data to the corresponding element in the clonedList (the new copy).现在我需要将该数据分配给clonedList (新副本)中的相应元素。 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我对 Java 不太了解,但你不能做

clonedList.add(n.data)

in your while loop to create a deep copy?在你的 while 循环中创建一个深拷贝?

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:如果您不需要深拷贝,您应该能够将克隆列表的head设置为原始列表的head ,例如:

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.在我看来,您有自己的LinkedList实现而没有add方法,因此要么编写一个,要么替换示例中的方法调用。

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.为不修改列表状态的方法要求实例是没有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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