细胞分裂法:

  1. 增殖:遍历next指针,拷贝旧节点,并将新节点插入到旧节点之后
  2. 复制:遍历next指针,如果某个节点的random不为空(旧节点),则下一个节点(新节点)的random指向该节点random指向节点的下一个节点
  3. 分裂:遍历next指针,将两个链表分裂开来

图片说明

代码如下:

//
// Created by jt on 2020/9/23.
//
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        // "增殖"
        if (!head) return nullptr;
        RandomListNode *p = head;
        while (p) {
            RandomListNode *q = new RandomListNode(p->label);
            q->next = p->next;
            p->next = q;
            p = q->next;
        }
        // "复制"
        p = head;
        while (p) {
            if (p->random) { p->next->random = p->random->next; }
            p = p->next->next;
        }
        // "分裂"
        p = head;
        RandomListNode *newHead = p->next;
        while (p) {
            RandomListNode *q = p->next;
            p->next = q->next;
            if (q->next) q->next = q->next->next;
            p = p->next;
        }
        return newHead;
    }
};