LeetCode || Copy List with Random Pointer

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:
map<RandomListNode *, RandomListNode *> mapNodes;
RandomListNode *newList = NULL;

return NULL;
while(p!=NULL){
RandomListNode *q = new RandomListNode(p->label);
mapNodes[p] = q;
newList = q;
}
else{
newList->next = q;
newList = newList->next;
}
p = p->next;
}
while(p!=NULL){
if(p->random!=NULL)
newList->random = mapNodes[p->random];      //注意这里要用p->random而不是p
p = p->next;
newList = newList->next;
}
}
};

newNode->ranodm = oldNode->random->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 *newList = NULL;

return NULL;
while(p!=NULL){
RandomListNode *q = new RandomListNode(p->label);
q->next = p->next;
p->next = q;

p = q->next;
}

while(p!=NULL){
if(p->random != NULL)
p->next->random = p->random->next;
p = p->next->next;
}

while(p!=NULL && p->next!=NULL){    //注意这里的条件，首先要判断p是否为null
}
else{
newList->next = p->next;
newList = newList->next;
}
p->next = newList->next;
p = p->next;
}

}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120