Pergunta de entrevista da empresa Amazon

Make a deep copy of a linked list that has a random link pointer and a next pointer.

Resposta da entrevista

Sigiloso

29 de ago. de 2012

According to the property of the list you describe there, I assume that it's some sort of Skip List. Let's think about the different of making a deep copy of a simple singly linked list, and making a deep copy of a list such as a skip list - we don't know if the node has been created or not. Therefore, we need to create all the nodes first. In a high level view, to make a copy of such a list can be done by the following steps: 1. Loop for the original list, and make copy of every node by extracting the "data" field from the original node, and create a new node with the same data you extract. At this moment, let's not worry about the pointers for the new node. 2. Loop over the new nodes, and update the pointers according to the original list. However, there is a VERY IMPORTANT step here. We need some sort of mapping between the nodes in the original list, and the ones in the new list. We could use a hashMap here, where the key is the original node, and the value is the new node. Overall, the running time should be O(2n), where space complexity is also O(2n) The actual implementation will be ignored here. (Note: for more information about Skip List, please refer to CLRS.)