AcWing 48. 复杂链表的复刻
原题链接
中等
作者:
adamXu
,
2020-09-27 23:00:44
,
所有人可见
,
阅读 420
/**
* Definition for singly-linked list with a random pointer.
* struct ListNode {
* int val;
* ListNode *next, *random;
* ListNode(int x) : val(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
ListNode *copyRandomList(ListNode *head) {
if(!head) return head;
for(auto p = head;p;){
auto next = p->next;
auto np = new ListNode(p->val);
p->next = np;
np->next = next;
p = p->next->next;
}
for(auto p = head;p;){
if(p->random) p->next->random = p->random->next;
p = p->next->next;
}
auto dummy = new ListNode(-1);
auto cur = dummy;
for(auto p = head;p;){
cur->next = p->next;
cur = cur->next;
p = p->next->next;
}
return dummy->next;
}
};