/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node() {}
Node(int _val, Node* _next, Node* _random) {
val = _val;
next = _next;
random = _random;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head)
return NULL;
Node *p=head;
while(p){ //相邻的复制一份
Node* s=new Node(p->val,p->next,NULL);
p->next=s;
p=s->next;
}
p=head;
while(p){ //复制随机指针
p->next->random=(p->random)?p->random->next:NULL;
p=p->next->next;
}
Node* ptr_old_list=head; //旧链表
Node* ptr_new_list=head->next; //新链表
Node* head_old=head->next; //保存返回指针
while(ptr_old_list){ //复制前后指针
ptr_old_list->next=ptr_old_list->next->next;
ptr_new_list->next=(ptr_new_list->next)?ptr_new_list->next->next:NULL;
ptr_old_list=ptr_old_list->next;
ptr_new_list=ptr_new_list->next;
}
return head_old;
}
};
138. 复制带随机指针的链表
最新推荐文章于 2022-04-22 16:27:46 发布