AcWing 48. 复杂链表的复刻
原题链接
中等
作者:
Value
,
2020-09-17 11:46:07
,
所有人可见
,
阅读 454
/**
* 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) {
ListNode *t = head;
while(t){
ListNode *p = new ListNode(t->val);
p->next = t->next;
t->next = p;
t = p->next;
}
t = head;
while(t){
if(t->random) t->next->random = t->random->next;
t = t->next->next;
}
ListNode *dummy = new ListNode(-1), *s = dummy;
t = head;
while(t){
s->next = t->next;
s = t->next;
t->next = t->next->next; // 复原
t = t->next;
}
s->next = NULL;
return dummy->next;
}
};