Search code examples
calgorithmdata-structureslinked-list

How do you copy a linked list into another list?


I'm studying data structures and linked lists, but I'm not getting the concept of how to make a copy of a linked list. Can someone explain this, possibly using pseudocode or C code?


Solution

  • The logic for duplicating a linked list is recursive and based on the following observations:

    1. The clone of the empty list is the empty list.
    2. The clone of a list with first node x and remaining nodes xs is a copy of x prepended to a clone of xs.

    If you encode the linked list in C++, this can be very clean:

    struct Node {
        int value;
        Node* next;
    };
    
    Node* Clone(Node* list) {
        if (list == NULL) return NULL;
    
        Node* result = new Node;
        result->value = list->value;
        result->next = Clone(list->next);
        return result;
    }