Copy List with Random Pointer问题及解法

来源:互联网 发布:unity3d游戏大全 编辑:程序博客网 时间:2024/06/07 16:12

问题描述:

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*> m;return bl(m, head);}RandomListNode * bl(unordered_map<RandomListNode*, RandomListNode*>& m, RandomListNode *head){if (head == NULL) return NULL;if (!m.count(head)){RandomListNode * root = new RandomListNode(head->label);m[head] = root;root->next = bl(m, head->next);root->random = bl(m, head->random);return root;}else return m[head];}};


原创粉丝点击