Deep Copy Constructor for Linked List in Java

3 min read 07-10-2024
Deep Copy Constructor for Linked List in Java


Deep Copying Linked Lists in Java: Avoiding the Pitfalls

When working with linked lists in Java, it's crucial to understand the distinction between shallow and deep copies. A shallow copy simply creates a new reference to the original list, meaning any changes made to the copied list will also affect the original. This can lead to unexpected behavior and data inconsistency.

A deep copy, on the other hand, creates a completely independent copy of the linked list, including all its nodes and their associated data. This ensures that modifications to the copy won't impact the original list.

Let's explore a scenario where a shallow copy can cause problems:

class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

class LinkedList {
    Node head;

    // Shallow copy constructor
    public LinkedList(LinkedList original) {
        this.head = original.head; 
    }
}

public class Main {
    public static void main(String[] args) {
        LinkedList original = new LinkedList();
        original.head = new Node(1);
        original.head.next = new Node(2);
        original.head.next.next = new Node(3);

        LinkedList copy = new LinkedList(original);
        copy.head.next.data = 10; // Modifying data in the copied list

        System.out.println("Original list:");
        printLinkedList(original);

        System.out.println("Copied list:");
        printLinkedList(copy);
    }

    public static void printLinkedList(LinkedList list) {
        Node current = list.head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
}

In this example, the LinkedList constructor creates a shallow copy. When we modify the data in the copied list, the corresponding node in the original list is also affected.

Output:

Original list:
1 10 3 
Copied list:
1 10 3 

The Problem: The change to the data in the copied list (copy.head.next.data = 10;) also affected the original list because both lists share the same underlying node structure.

Solution: A deep copy constructor is required to create an independent copy of the linked list. This involves creating new nodes for each element in the original list and copying the data accordingly.

class LinkedList {
    Node head;

    // Deep copy constructor
    public LinkedList(LinkedList original) {
        if (original.head == null) {
            this.head = null;
            return;
        }

        this.head = new Node(original.head.data);
        Node originalCurrent = original.head.next;
        Node copyCurrent = this.head;

        while (originalCurrent != null) {
            copyCurrent.next = new Node(originalCurrent.data);
            copyCurrent = copyCurrent.next;
            originalCurrent = originalCurrent.next;
        }
    }
}

Explanation:

  1. We initialize the head of the copy to null if the original list is empty.
  2. We create a new node in the copy list with the data of the original list's head node.
  3. We iterate through the original list, creating a new node in the copy list for each node in the original list.
  4. The next pointer of each newly created node in the copy list is set to the next node in the copy list.

Benefits of a Deep Copy:

  • Data Independence: Changes to the copied list won't affect the original.
  • Data Integrity: A deep copy ensures the data in the original list remains unchanged.
  • Error Prevention: It avoids unintended modifications to the original list due to shared references.

Conclusion:

Understanding the difference between shallow and deep copies is crucial for maintaining data integrity and avoiding potential bugs. By implementing a deep copy constructor, you can ensure that your linked lists are properly cloned and that changes to one list won't affect the other. This is especially important in situations where you need to manipulate multiple copies of a list independently.

Additional Resources: