拷贝有随机指针的链表
拷贝有随机指针的链表
http://www.nowcoder.com/questionTerminal/60e43001345241ba9266cb4ee6fc6350
细胞分裂法:
- 增殖:遍历next指针,拷贝旧节点,并将新节点插入到旧节点之后
- 复制:遍历next指针,如果某个节点的random不为空(旧节点),则下一个节点(新节点)的random指向该节点random指向节点的下一个节点
- 分裂:遍历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; } };
刷遍天下无敌手 文章被收录于专栏
秋招刷题历程