1 题目
题目:克隆带随机指针的链表(Copy List with Random Pointer)
描述:给出一个链表,每个节点包含一个额外增加的随机指针,其可以指向链表中的任何节点或空的节点。返回其链表的深度拷贝。
lintcode题号——105,难度——medium
2 解决方案
2.1 思路
对链表的深拷贝,可以参考对图的克隆操作,先找到点、克隆点,再建立旧节点到新节点的映射,最后再克隆点的其余附属物品,本题中节点的附属物品为尾指针和随机指针。
2.3 时间复杂度
时间复杂度为O(n)。
2.4 空间复杂度
使用map数据结构,空间复杂度为O(n)。
3 源码
细节:
- 先克隆节点,并建立旧节点到新节点的映射关系。
- 再克隆尾指针、随即指针。
C++版本:
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
RandomListNode *copyRandomList(RandomListNode *head) {
// write your code here
if (head == nullptr)
{
return head;
}
// 克隆点,并建立 旧-新 映射
map<RandomListNode *, RandomListNode *> nodeMap;
RandomListNode * cur = head;
while (cur != nullptr)
{
nodeMap.insert({cur, new RandomListNode(cur->label)});
cur = cur->next;
}
// 克隆尾指针和随机指针
for (auto it : nodeMap)
{
if (it.first->next != nullptr)
{
it.second->next = nodeMap.at(it.first->next);
}
if (it.first->random != nullptr)
{
it.second->random = nodeMap.at(it.first->random);
}
}
return nodeMap.at(head);
}