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;
}
source
share