A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
思路:
因为是深度拷贝,所以我们需要先将链表整个复制下来,然后再处理随机指针。提供两种处理方案:1 暴力搜索,即找出每个随机指针指向的结点;2 使用哈希表,将结点的地址记录好,然后进行映射。
1 暴力搜索
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL) return NULL;
RandomListNode* res = NULL, *curr = NULL, *resCurr = NULL;
curr = head;
while (curr){
if (!res){
res = new RandomListNode(curr->label);
resCurr = res;
curr = curr->next;
continue;
}
else resCurr->next = new RandomListNode(curr->label);
curr = curr->next;
resCurr = resCurr->next;
}
curr = head;
resCurr = res;
while (curr){
if (curr->random){
RandomListNode* tmp = head;
RandomListNode* resTmp = res;
while (tmp){
if (tmp->random == curr){
curr->random = resTmp;
break;
}
tmp = tmp->next;
resTmp = resTmp->next;
}
}
curr = curr->next;
resCurr = resCurr->next;
}
return res;
}
2 使用哈希表
RandomListNode *copyRandomList2(RandomListNode *head){
if (!head) return NULL;
unordered_map<RandomListNode*, int> ptrToint;
unordered_map<int, RandomListNode*> intToptr;
RandomListNode* res = NULL, *curr = NULL, *resCurr = NULL;
res = new RandomListNode(head->label);
resCurr = res;
curr = head;
ptrToint[head] = 0;
intToptr[0] = res;
int count = 1;
while (curr->next){
resCurr->next = new RandomListNode(curr->next->label);
curr = curr->next;
resCurr = resCurr->next;
intToptr[count] = resCurr;
ptrToint[curr] = count;
count++;
}
curr = head;
resCurr = res;
while (curr){
int a = ptrToint[curr->random];
if (curr->random)
resCurr->random = intToptr[ptrToint[curr->random]];
curr = curr->next;
resCurr = resCurr->next;
}
return res;
}