[leetcode 138]Copy List with Random Pointer

来源:互联网 发布:怎么远程授权php 编辑:程序博客网 时间:2024/04/30 03:59

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) {        unordered_map<RandomListNode*, RandomListNode*> old2new;        RandomListNode *old_cur = head;        RandomListNode* dummy = new RandomListNode(-1);        RandomListNode* new_cur = dummy;        while (old_cur) {            RandomListNode *newNode = new RandomListNode(old_cur->label);            old2new[old_cur] =newNode;            new_cur->next = newNode;            new_cur = new_cur->next;            old_cur = old_cur->next;        }        old_cur = head;        while (old_cur) {            old2new[old_cur]->random = old2new[old_cur->random];            old_cur = old_cur->next;        }        return dummy->next;    }};


0 0