要求我们深度复制链表。 这里要求新链表中的各个节点及每个节点的next和random节点都必须是新链表中的元素。 由于加入了random节点,该节点既可能在当前节点之前,也可能在之后出现。 因而不能扫描一遍,需要扫描两遍。在第一遍中先让新链表的每个节点的random节点指向旧链表的相应节点,同时要建立旧链表和新链表相应节点的对应。 在第二遍扫描时更新random节点为对应的新链表节点即可。
/**
* 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 *newH = new RandomListNode(0);
RandomListNode *res = newH;
map<RandomListNode*,RandomListNode*> repository;
RandomListNode *st = head;
while( st != NULL )
{
RandomListNode *tmp = new RandomListNode(st->label);
//tmp.next = st.next;
if( st->random != NULL )
{
tmp->random = st->random;
}
else
{
tmp->random = NULL;
}
res->next = tmp;
repository[st] = tmp;
res = res->next;
st = st->next;
}
st = newH->next;
while( st != NULL )
{
st->random = repository[st->random];
st = st->next;
}
return newH->next;
}
};