题目:
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.
解题思路:
采用递归求解,并利用unordered_map来记录新生成的节点。
代码:
/** * 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: unordered_map<int, RandomListNode*> dict; RandomListNode *copyRandomList(RandomListNode *head) { if (head == NULL || dict.count(head->label)) return NULL; RandomListNode *new_head = new RandomListNode(head->label); dict[head->label] = new_head; if (head->next != NULL) { copyRandomList(head->next); new_head->next = dict[head->next->label]; } if (head->random != NULL) { copyRandomList(head->random); new_head->random = dict[head->random->label]; } return new_head; } };