Leetcode 138题解题
https://leetcode-cn.com/problems/copy-list-with-random-pointer/
给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。构造这个链表的 深拷贝。返回复制链表的头节点。
解题思路:
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
struct Node* copyRandomList(struct Node* head) {
if(head == NULL){
return NULL;
}
struct Node* cur = head;
while(cur){
struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
copy->val = cur->val;
copy->next = cur->next;
cur->next = copy;
cur = copy->next;
}
cur = head;
while(cur){
struct Node *copy = cur->next;
if(cur->random != NULL){
copy->random = cur->random->next;
}else{
copy->random = NULL;
}
cur = copy->next;
}
struct Node *newlist = (struct Node*)malloc(sizeof(struct Node));
newlist->next = NULL;
struct Node *tail = newlist;
cur = head;
struct Node *copy;
struct Node* tmp;
while(cur){
copy = cur->next;
tmp = copy->next;
copy->next = tail->next;
tail->next = copy;
tail = copy;
cur->next = tmp;
cur = tmp;
}
struct Node *ret = newlist->next;
free(newlist);
newlist->next = NULL;
return ret;
}