Leetcode 138. 复制带随机指针的链表
/**
* 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;
struct Node* curNext = head->next;
while(cur != NULL)
{
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->next = NULL;
newnode->random = NULL;
newnode->val = cur->val;
cur->next = newnode;
newnode->next = curNext;
cur = curNext;
if(curNext != NULL)
{
curNext = curNext->next;
}
}
cur = head;
curNext = head->next;
//第二步 设计 radom
while(cur != NULL)
{
if(cur->random == NULL)
{
curNext->random = NULL;
}
else
{
curNext->random = cur->random->next;
}
cur = curNext->next;
if(cur != NULL)
{
curNext = cur->next;
}
}
//第三步
cur = head;
curNext = head->next;
struct Node* newHead = NULL;
struct Node* tail = NULL;
while(cur != NULL)
{
cur->next = curNext->next;
if(newHead == NULL)
{
newHead = curNext;
tail = newHead;
}
else
{
tail->next = curNext;
tail = tail->next;
}
cur = cur->next;
if(cur != NULL)
{
curNext = cur->next;
}
}
return newHead;
}