Leetcode 138. 复制带随机指针的链表

/**
 * 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*> A;
    RandomListNode *copyRandomList(RandomListNode *head) {
        if(!head) return head;
        RandomListNode *p=new RandomListNode(head->label);
        A[head]=p;
        if(head->next){
            if(!A.count(head->next)) p->next=copyRandomList(head->next);
            else p->next=A[head->next];
        }
        if(head->random){
            if(!A.count(head->random)) p->random=copyRandomList(head->random);
            else p->random=A[head->random];
        }
        return p;
    }
};

猜你喜欢

转载自blog.csdn.net/bendaai/article/details/81002970