Search code examples
javamethodslinked-listcopy-constructor

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


I am working on a project for my Data Structures class that asks me to write a class to implement a linked list of ints.

  • Use an inner class for the Node.
  • Include the methods below.
  • Write a tester to enable you to test all of the methods with whatever data you want in any order.

I have to create three different constructors. One of the constructors is a copy constructor. I have my code down below showing what I did but I'm not sure I wrote this constructor correctly. I also have a method called addToFront one of the many methods I need to implement in this project. Can someone let me know what I would need to write for the copy constructor? I have no idea what I need to write for a copy constructor. I've tried looking it up but the examples shown don't match with what I'm trying to write.

public class LinkedListOfInts {
    Node head;

    private class Node {
        int value;
        Node nextNode;

        public Node(int value, Node nextNode) {
            this.value = value;
            this.nextNode = nextNode;
        }

    }
    
    public LinkedListOfInts() {
        
    }
    
    public LinkedListOfInts(LinkedListOfInts other) {
        
    }

    public void addToFront(int x) {
        head = new Node(x, head);
    }

    public String toString() {
        String result = " ";
        for (Node ptr = head; ptr != null; ptr = ptr.nextNode)
            result += ptr.value + " ";
        return result;
    }

    public static void main(String[] args) {
        LinkedListOfInts list = new LinkedListOfInts();
        for (int i = 0; i < 15; i++)
            list.addToFront(i);
        System.out.println(list);
    }

}

Solution

  • 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);
    }