一样的代码,现在提交通过不了!!!
提示不能修改原链表
把代码修改一下就可以过了!
C++ 代码
```
class Solution {
public:
ListNode *copyRandomList(ListNode *head) {
for(auto p = head; p;) {
auto np = new ListNode(p->val);
auto next = p->next;
p->next = np;
np->next = next;
p = next;
}
for(auto p=head; p;p=p->next->next){
if(p->random)
p->next->random = p->random->next;
}
auto dummy = new ListNode(-1);
auto cur = dummy;
for(auto p= head; p;) {
auto pre = p;
cur->next = p->next;
cur = cur->next;
p = p->next->next;
pre->next = p;
}
return dummy->next;
}
};
```
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度分析:blablabla
C++ 代码
blablabla