题目链接: leetcode.
错误思路,修改了原来的列表指针
[[7,null],[13,0],[11,4],[10,2],[1,0]]
Next pointer of node with label 7 from the original list was modified.
/*
// 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) {
if(head == nullptr)
return NULL;
Node* node1 = head;
Node* ans = new Node(0);
Node* node2 = ans;
//复制所有节点,新的random指向旧的节点
while(node1)
{
node2 -> next = new Node(node1 -> val);
node2 = node2 -> next;
if(node1 -> random)
node2 -> random = node1 -> random;
node1 = node1 -> next;
}