一直segmentfault的代码
class Solution {
public:
ListNode *copyRandomList(ListNode *head) {
ListNode* new_head = new ListNode(-1);
new_head->next = head;
ListNode* p = new_head->next;
while(p) {
ListNode* q = new ListNode(p->val);
q->next = p->next;
p->next = q;
p = q->next;
}
p = new_head->next;
//第18行导致segmentfault,原因是p可能是空啊,
new_head->next = p->next;
while(p) {
if(p->random) {
p->next->random = p->random->next;
}
ListNode* res = p->next->next;
p = res;
}
// return new_head->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; p = p->next)
{
cur->next = p->next;
cur = cur->next;
p->next = p->next->next;
}
return dummy->next;
}
};