Copy List with Random Pointer

来源:互联网 发布:windows vista重装 编辑:程序博客网 时间:2024/06/10 20:20

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.


Solution:

/** * 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 *res = new RandomListNode(-1);        unordered_map<RandomListNode*, int> umRI;        unordered_map<int, RandomListNode*> umIR;        RandomListNode *p = head, *q = res;        int num = 0;        while(p)        {            RandomListNode* node = new RandomListNode(p->label);            q->next = node;            q = q->next;            umIR[++num] = q;            umRI[p] = num;            p = p->next;        }        q->next = NULL;        p = head;        q = res->next;        while(p)        {            if(!p->random) q->random = NULL;            else            {                num = umRI[p->random];                q->random = umIR[num];            }            p = p->next;            q = q->next;        }        return res->next;    }};


0 0
原创粉丝点击