题目大意:链表中的结点有两个指针域,一个next,一个random,克隆这个链表
分析:
方法一:类似leetcode133,DFS+MAP。
方法二:O(1)空间复杂度。参考leetcode题解。
代码:
方法一:
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
map<Node*,Node*> m;
Node* copyRandomList(Node* head) {
if(head == NULL) return head;
if(m.count(head) != 0) return m[head];
Node* node = new Node(head->val);
m[head] = node;
node->next = copyRandomList(head->next);
node->random = copyRandomList(head->random);
return node;
}
};