How to copy a linked list to another list?

I study data structures and linked lists, but I don't understand how to make a copy of a linked list. Can someone explain this, possibly using pseudocode or C code?

+5
source share
2 answers

The duplicate logic of a linked list is recursive and based on the following observations:

  • The clone of an empty list is an empty list.
  • The list clone with the first node x and the remaining xs nodes is a copy of x added to the xs clone.

If you encode a 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;
}
+17
source

, node ? , (, ) ? ( ListA, , node ListB).

+5

All Articles