[英]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? 有人可以解释一下,可能使用伪代码或C代码吗?
The logic for duplicating a linked list is recursive and based on the following observations: 复制链表的逻辑是递归的,并基于以下观察:
If you encode the linked list in C++, this can be very clean: 如果用C ++编码链表,这可能非常干净:
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;
}
Do you understand how to add a new node to an existing list? 您是否了解如何将新节点添加到现有列表? And do you understand how to traverse (ie 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). 复制列表只是同时执行这两个操作(遍历ListA;对于每个元素,复制元素并将其作为新节点添加到ListB)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.