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.
忽略random pointer这个干扰项,先把链表复制出来。然后再复制random pointer,为了这个要在第一次复制时记录好map。
= =划归真是个好东西。。。
尼玛昨天晚上写的,今天一运行竟然有BUG!胡乱折腾以后,认为自己不会用指针!终于在午睡睡醒以后把BUG调出来了。。。果然lab2是个磨练意志的好玩意,祖国大好青年我再也不怕BUG了!
/**
* 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 {
map<RandomListNode *, RandomListNode *> mapping;
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (!head) return NULL;
RandomListNode *ans = new RandomListNode(head->label);
mapping[head] = ans;
/* copy without random pointer */
RandomListNode *old = head;
RandomListNode *cur = ans;
while (old->next) {
old = old->next;
cur -> next = new RandomListNode(old->label);
cur = cur->next;
mapping[old] = cur;
}
/* copy random pointer */
old = head;
cur = ans;
while (old) {
if (old->random)
cur -> random = mapping[old->random];
old = old->next;
cur = cur->next;
}
return ans;
}
};