解题思路一:使用hashmap保存原链表节点的地址,和新链表中对应节点地址。第一次对原链表进行遍历同时初始化新链表。第二次对原链表进行遍历,同时对新链表中节点的random指针进行赋值。时间复杂度为O(n),空间复杂度为O(n)。
/**
* 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) {}
* };
*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
RandomListNode *src = head;
RandomListNode *dummy = new RandomListNode(0);
RandomListNode *dst = dummy;
map<RandomListNode*,RandomListNode*> dict;
while(src){
dst->next = new RandomListNode(src->label);
dst->next->random = src->random;
dict.insert({src,dst->next});
dst = dst->next;
src = src->next;
}
dst = dummy;
while(dst->next){
if(dst->next->random)
dst->next->random = dict.at(dst->next->random);
dst = dst->next;
}
return dummy->next;
}
};
解题思路二:
An intuitive solution is to keep a hash table for each node in the list, via which we just need to iterate the list in 2 rounds respectively to create nodes and assign the values for their random pointers. As a result, the space complexity of this solution is O(N), although with a linear time complexity.
As an optimised solution, we could reduce the space complexity into constant. The idea is to associate the original node with its copy node in a single linked list. In this way, we don't need extra space to keep track of the new nodes.
The algorithm is composed of the follow three steps which are also 3 iteration rounds.
Iterate the original list and duplicate each node. The duplicate
of each node follows its original immediately.
Iterate the new list and assign the random pointer for each
duplicated node.
Restore the original list and extract the duplicated nodes.
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(!head)
return head;
RandomListNode *src,*dst,*newhead;
for(src=head;src!=NULL;src=src->next->next){
dst = new RandomListNode(src->label);
dst->next = src->next;
src->next = dst;
}
for(src=head;src!=NULL;src = src->next->next){
dst = src->next;
if(src->random)
dst->random = src->random->next;
}
newhead = head->next;
dst = newhead;
for(src=head;src!=NULL;src= src->next){
src->next = dst->next;
if(dst->next)
dst->next = dst->next->next;
dst = dst->next;
}
return newhead;
}
};