How do you copy a linked list into another list?

落爺英雄遲暮 提交于 2019-12-18 17:25:41

问题


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:

  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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!