C语言 你如何将一个链表复制到另一个列表中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4984071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:46:18  来源:igfitidea点击:

How do you copy a linked list into another list?

calgorithmdata-structureslinked-list

提问by mr_eclair

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 代码吗?

回答by templatetypedef

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.
  1. 空列表的克隆是空列表。
  2. 具有第一个节点 x 和其余节点 xs 的列表的克隆是 x 的副本附加到 xs 的克隆。

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

回答by Oliver Charlesworth

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).

您了解如何将新节点添加到现有列表中吗?您是否了解如何遍历(即迭代)列表?复制列表只是同时执行这两个操作(遍历 ListA;对于每个元素,复制该元素并将其作为新节点添加到 ListB)。