August 1st, 2024

Deep list copy: More than meets the eye

The article presents a C programming challenge on deep copying a linked list with arbitrary node references, offering efficient solutions using interleaving and an intrusive hash map for memory management.

Read original articleLink Icon
Deep list copy: More than meets the eye

The article discusses a complex C programming challenge involving the deep copying of a linked list where each node has a reference to another arbitrary node in the list. The author presents a conventional approach that involves traversing the original list and allocating new nodes, but highlights the difficulty of resolving the references due to their identity rather than value. A naive solution would result in quadratic time complexity, which is inefficient for larger lists.

To improve efficiency, the author proposes a method that temporarily modifies the original list to interleave the new nodes with the old ones, allowing for linear time complexity. This method, however, is not suitable for concurrent access or read-only memory scenarios.

An alternative solution involves using an intrusive hash map that does not modify the original list. This approach utilizes a hash trie structure embedded within the linked list nodes, allowing for efficient mapping of old nodes to new nodes without altering the original list. The author provides a detailed implementation of this solution, emphasizing its elegance and utility in memory management.

The article concludes by inviting readers to explore the provided source code and tests, which are available for experimentation.

Link Icon 2 comments
By @layer8 - 6 months
Another solution is to fork() the process. ;)