且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-01-19 07:39:19

复制链表的逻辑是递归的,基于以下观察:

The logic for duplicating a linked list is recursive and based on the following observations:

  1. 空列表的克隆是空列表.
  2. 具有第一个节点 x 和其余节点 xs 的列表的克隆是 x 的副本附加到 xs 的克隆.

如果你用 C++ 编码链表,这会很干净:

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