RandomListNode *copyRandomList(RandomListNode *head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
//three steps
//1. 为原链表中每个节点创建一个shallow copy,用next指针指向这个copy节点。
//2. 利用原链表的next指针,将新链表的random指针指向正确的节点。
//3. 将两个链表分开。
if(!head)
return NULL;
RandomListNode* cur = head,*next;
RandomListNode* copy;
// 1.
while(cur)
{
next = cur->next;
copy = new RandomListNode(cur->label);
cur->next = copy;
copy->next = next;
cur = next;
}
//2.
cur = head;
while(cur)
{
copy = cur->next;
if(cur->random)
copy->random = cur->random->next;
cur = copy->next;
}
//3.
RandomListNode* newHead = head->next;
copy = newHead;
head->next = copy->next;
cur = copy->next;
while(cur)
{
copy->next = cur->next;
copy = copy->next;
cur->next = copy->next;
cur = cur->next;
}
return newHead;
}