typedef struct Node
{
int data;
Node *next;
Node *other;
};
Node *pHead;
pHead
is a singly linked list. The next
field points to the next element in the list. The other
field may point to any other element (could be one of the previous nodes or one of the nodes ahead) in the list or NULL
.
How does one write a copy function that duplicates the linked list and its connectivity? None of the elements (next
and other
) in the new list should point to any element in the old list.
Create a new node for every node in the old list, copy the corresponding data and make the next pointer of the nodes in the new list point to their successor in the new list, forgetting the other
pointer for time being. At the time of creating a new node remember the mapping of node address something like:
Old_list New_list
-------------------
0x123 0x345 [ addresses of the first node]
0xabc 0xdef [ addresses of the second node]
...
In the second pass pass for every node in the new list consider its other
pointer and find its corresponding node in the new list from the map and use it as the other
pointer of this node (node in the new list).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With