问题
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?
回答1:
The logic for duplicating a linked list is recursive and based on the following observations:
- The clone of the empty list is the empty list.
- 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;
}
回答2:
Do you understand how to add a new node to an existing list? And do you understand how to traverse (i.e. iterate over) a list? Copying a list is just performing both of these operations simultaneously (traverse ListA; for each element, copy the element and add it as a new node to ListB).
来源:https://stackoverflow.com/questions/4984071/how-do-you-copy-a-linked-list-into-another-list