A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
/**
* 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:
struct comp
{
bool operator()(const RandomListNode* ls, const RandomListNode* rs)
{
return ls->label < rs->label;
}
};
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL)
{
return NULL;
}
RandomListNode *now = head;
RandomListNode *copyNow = NULL;
map<RandomListNode*, RandomListNode*> relation;
while (now)
{
copyNow = new RandomListNode(now->label);
copyNow->random = NULL;
copyNow->next = NULL;
relation.insert(pair<RandomListNode*,RandomListNode*>(now, copyNow));
now = now->next;
}
now = head;
while (now)
{
copyNow = relation.find(now)->second;
if (now->next)
{
copyNow->next = relation.find(now->next)->second;
}
if (now->random)
{
copyNow->random = relation.find(now->random)->second;
}
now = now->next;
}
return relation.find(head)->second;
}
};
方法二:在每个节点下面复制一排相同结点,不用map保持新旧结点的联结,而是通过新旧结点的next值。
/**
* 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) {
if (head == NULL)
{
return NULL;
}
RandomListNode *now = head;
RandomListNode *copyNow = NULL;
while (now)
{
copyNow = new RandomListNode(now->label);
copyNow->random = now;
copyNow->next = now->next;
RandomListNode *next_now = now->next;
now->next = copyNow;
now = next_now;
}
RandomListNode *copy_head = head->next;
while (copy_head)
{
if (copy_head->random->random)
{
copy_head->random = copy_head->random->random->next;
}
else
{
copy_head->random = NULL;
}
if (copy_head->next)
{
copy_head = copy_head->next->next;
}
else
{
copy_head = NULL;
}
}
copy_head = head->next;
now = head;
copyNow = copy_head;
while (now)
{
now->next = now->next->next;
if (copyNow->next)
{
copyNow->next = copyNow->next->next;
}
else
{
copyNow->next = NULL;
}
now = now->next;
copyNow = copyNow->next;
}
return copy_head;
}
};
方法三:在每个结点后面复制此结点,第一遍复制next和值,第二遍复制random值,第三遍解next