0
Follow
0
View

Did I write the copy constructor for my Linked List program correctly?

ddhhhnj 注册会员
2023-01-24 22:39

You can iterate over the nodes of the other list and sequentially create new tail nodes based on their values.

public LinkedListOfInts(LinkedListOfInts other) {
    Node tail = null;
    for(Node n = other.head; n != null; n = n.nextNode){
        if(tail == null) this.head = tail = new Node(n.value, null);
        else {
            tail.nextNode = new Node(n.value, null);
            tail = tail.nextNode;
        }
    }
}
// ...
public static void main(String[] args) {
    LinkedListOfInts list = new LinkedListOfInts();
    for (int i = 0; i < 15; i++)
        list.addToFront(i);
    LinkedListOfInts copy = new LinkedListOfInts(list);
    System.out.println(list);
    System.out.println(copy);
}