题目
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的深度拷贝。
代码
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL)
return head;
RandomListNode* cur = head;
while (cur != NULL) {
RandomListNode* newNode = new RandomListNode(cur->label);
newNode->next = cur->next;
cur->next = newNode;
cur = newNode->next;
}
cur = head;
while (cur != NULL) {
if (cur->random != NULL) {
cur->next->random = cur->random->next;
}
cur = cur->next->next;
}
cur = head->next;
RandomListNode* newHead = cur;
RandomListNode* old = head;
while (old != NULL) {
old->next = old->next->next;
if (old->next != NULL) {
cur->next = old->next->next;
}
cur = cur->next;
old = old->next;
}
return newHead;
}
};