题目描述
白话题目:
算法:
详细解释关注 B站 【C语言全代码】学渣带你刷Leetcode 不走丢 https://www.bilibili.com/video/BV1C7411y7gB
C语言完全代码
/**
* Definition for a Node.
* struct Node {
* int val;
* struct TreeNode *next;
* struct TreeNode *random;
* };
*/
struct Node* copyRandomList(struct Node* head) {
if(!head) return NULL;
/*使用next将整个链表构建起来*/
struct Node *head1 = (struct Node *)malloc(sizeof(struct Node));
head1->val = head->val;
head1->next = NULL;
head1->random = NULL;
struct Node* h = head, * h1 = head1;
while(h->next){
h = h->next;
struct Node * temp = (struct Node *)malloc(sizeof(struct Node));
temp->val = h->val;
temp->next = NULL;
temp->random = NULL;
h1->next = temp;
h1 = h1->next;
}
/*处理那个随机指针*/
h = head; h1 = head1;
while(h){
if(!h) break;
int index=0;
struct Node * cur=head, * cur1=head1;
if(h->random){
while(cur && cur!=h->random){
index++;
cur = cur->next;
}
while(index){
index--;
cur1 = cur1->next;
}
h1->random = cur1;
}
else h1->random = NULL;
h = h->next;
h1 = h1->next;
}
return head1;
}