leetcode 138. Copy List with Random Pointer

来源:互联网 发布:本拉登 中国 知乎 编辑:程序博客网 时间:2024/06/14 03:56

138. 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:    RandomListNode *copyRandomList(RandomListNode *head)     {        if (!head)            return NULL;        map<RandomListNode *,RandomListNode *> copy;        //copy point        RandomListNode *p = head;        while(p)        {            copy[p] = new RandomListNode(p->label);            p = p->next;        }        // copy next and random        p = head;        while(p)        {            copy[p]->next = copy[p->next];            copy[p]->random = copy[p->random];            p = p->next;        }        return copy[head];    }};


原创粉丝点击