struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead) {
if (pHead == nullptr)
{
return nullptr;
}
unordered_map<RandomListNode*, RandomListNode*> mp;
RandomListNode* pNewHead = new RandomListNode(0);
RandomListNode* curNode = pHead;
RandomListNode* newCurNode = pNewHead;
while (curNode)
{
RandomListNode* newNode = new RandomListNode(curNode->label);
newCurNode->next = newNode;
mp[curNode] = newNode;
curNode = curNode->next;
newCurNode = newCurNode->next;
}
for(auto var : mp)
{
var.second->random = var.first->random == nullptr ? nullptr : mp[var.first->random];
}
return pNewHead->next;
}
};
package main
type RandomListNode struct {
Label int
Next *RandomListNode
Random *RandomListNode
}
func Clone(head *RandomListNode) *RandomListNode {
if head == nil {
return nil
}
mp := make(map[*RandomListNode]*RandomListNode, 0)
newHead := new(RandomListNode)
newCurNode := newHead
curNode := head
for curNode != nil {
newNode := new(RandomListNode)
newNode.Label = curNode.Label
newCurNode.Next = newNode
mp[curNode] = newNode
curNode = curNode.Next
newCurNode = newCurNode.Next
}
for key, value := range mp {
if key.Random != nil {
value.Random = mp[key.Random]
} else {
value.Random = nil
}
}
return newHead.Next
}