思路
常规方案就是map记录前后节点的映射关系,然后根据random指针找到新节点地址,时间复杂度O(n)。
不使用map的方案是,将新节点挂载在老节点的next,这样新节点random的只需要让通过老节点的random访问next即可,最后在分离新旧链表。
实现
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head) { return head;}
Node *pNew;
Node *pNode = head;
Node *pNext;
while (pNode) {
pNew = new Node(pNode->val);
pNext = pNode->next;
pNode->next = pNew;
pNew->next = pNext;
pNode = pNext;
}
pNode = head;
while (pNode) {
if (pNode->random) {
pNode->next->random = pNode->random->next;
}
pNode = pNode->next->next;
}
Node vHead(0);
Node *pList = &vHead;
pNode = head;
while (pNode) {
pList->next = pNode->next;
pNext = pNode->next->next;
pNode->next = pNext;
pNode = pNext;
pList = pList->next;
}
return vHead.next;
}
};