两趟循环,第一轮复制节点和next,并建立新旧节点之间的映射。
第二轮复制random
/**
* Definition for singly-linked list with a random pointer.
* struct ListNode {
* int val;
* ListNode *next, *random;
* ListNode(int x) : val(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
ListNode *copyRandomList(ListNode *head) {
if(head == NULL)return NULL;
unordered_map<ListNode*, ListNode*> map;
ListNode* dummy = new ListNode(0x7f7f7f7f);
ListNode* cur = dummy;
ListNode* head_backup = head;
while(head != NULL){
ListNode* p = new ListNode(head->val);
cur->next = p;
cur = cur->next;
map[head] = cur;
head = head->next;
}
cur = dummy->next;
while(head_backup){
cur->random = map[head_backup->random];
cur = cur->next;
head_backup = head_backup->next;
}
return dummy->next;
}
};