![fb0d7592da2e5fd4935f1b44ff801a0e.png](https://i-blog.csdnimg.cn/blog_migrate/99a58ad1a352ca50318d383b4649d55c.jpeg)
题目来源于 LeetCode 上第 138 号问题:复制带随机指针的链表。题目难度为 Medium,目前通过率为 40.5% 。
题目描述
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的深拷贝。
题目解析
- 在原链表的每个节点后面拷贝出一个新的节点
- 依次给新的节点的随机指针赋值:cur->next->random = cur->random->next
- 断开链表可得到深度拷贝后的新链表
之所以说这个方法比较巧妙是因为相较于一般的解法(如使用 Hash map )来处理,上面这个解法 不需要占用额外的空间。
动画描述
![78449535b6abb0f661ee2b6934e313fa.gif](https://i-blog.csdnimg.cn/blog_migrate/5576786db1ee4a4bb439ba44a07e23be.gif)
代码实现
我发现带指针的题目使用 C++ 版本更容易描述,所以下面的代码实现是 C++ 版本。
class Solution {public: RandomListNode *copyRandomList(RandomListNode *head) { if (!head) return NULL; RandomListNode *cur = head; while (cur) { RandomListNode *node = new RandomListNode(cur->label); node->next = cur->next; cur->next = node; cur = node->next; } cur = head; while (cur) { if (cur->random) { cur->next->random = cur->random->next; } cur = cur->next->next; } cur = head; RandomListNode *res = head->next; while (cur) { RandomListNode *tmp = cur->next; cur->next = tmp->next; if(tmp->next) tmp->next = tmp->next->next; cur = cur->next; } return res; }};