- 拷贝节点链接在原节点后面
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
struct Node* copyRandomList(struct Node* head) {
struct Node* cur = head;
while(cur)
{
struct Node* next = cur->next;
struct Node* copy = (struct Node*)malloc (sizeof(struct Node));
copy -> val = cur ->val;
cur ->next = copy;
copy ->next = next;
cur = next;
}
}
- 处理拷贝节点的random
通过规律可知,拷贝节点的random 为其原节点的 random的next
cur =head;
while(cur)
{
struct Node* copy = cur ->next;
if(cur -> random == NULL)
copy -> random = NULL;
else
copy ->random = cur ->random ->next;
cur = copy ->next;
}
}
- 解下拷贝节点,分别链接原节点和拷贝节点。
cur = head;
struct Node* copyHead,*copyTail;
copyHead = copyTail = (struct Node*) malloc (sizeof(struct Node));
while(cur)
{
struct Node* copy = cur -> next;
struct Node* next = copy ->next;
copyTail -> next = copy;
copyTail = copyTail ->next;
cur -> next = next;
cur = next;
}
struct Node* guard = copyHead;
copyHead = copyHead-> next;
free(guard);
guard ==NULL;
return copyHead;
遇到这个报错,输入为NULL
我们加上判空
if(head == NULL)
return NULL;```