示例 1:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例 2:
输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]
示例 3:
输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]
示例 4:
输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 null。
提示:
-10000 <= Node.val <= 10000
Node.random 为空(null)或指向链表中的节点。
节点数目不超过 1000 。
用一个二维数组记录对应random的对应即可
注意head == nullptr时,直接返回nullptr,别返回没开辟空间的指针
/* // 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: Node* copyRandomList(Node* head) { int corres[1100]; Node* node[1010]; if(head == nullptr) return nullptr; Node* p = head; int i = 0, n = 0; while(p) { if(p->random == nullptr) corres[i] = -1; else { Node* t = head; int j = 0; while(t) { if(p->random == t) { corres[i] = j; break; } t = t->next; j++; } } node[i] = new Node(p->val); p = p->next; i++; } n = i; i = 0; p = head; while(p) { if(i < n - 1) node[i]->next = node[i + 1]; else node[i]->next = nullptr; if(corres[i] == -1) node[i]->random = nullptr; else node[i]->random = node[corres[i]]; i++; p = p->next; } return node[0]; } };