Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 828
Vishwanath Dalvi Avatar asked Feb 13 '11 12:02

Vishwanath Dalvi


People also ask

How do I copy a linked list to another linked list?

First create a single linked list with only the 'next' pointer and use a mapping to map the new nodes to their corresponding nodes in the given linked list. Now use this mapping to point the arbitrary node from any node in the newly created list.

How do I copy a linked list to another in python?

Take a linked list with the data field and pointer to the address of its random node. A function copyRandomList(listnode*head) takes the head node of the original list as the input and returns the deep copy of the list. If the head is empty, then the list is empty and we have to return the head as well.

Can you put a linked list in a linked list?

You can put any object in a list, including another list. If you want to add specific methods to this list of lists, you can create a subclass of LinkedList (or List , or any other List subclasses) or you can create a class with the list of lists as a field and add methods there to manipulate the list.


2 Answers

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;
}
like image 119
templatetypedef Avatar answered Nov 06 '22 16:11

templatetypedef


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

like image 33
Oliver Charlesworth Avatar answered Nov 06 '22 17:11

Oliver Charlesworth