关键点:通过“相互插入”式的复制方法来把源链表和目标链表的random联系起来。
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
typedef int LDataType;
typedef struct Node Node;
Node* BuyNode(LDataType x)
{
Node* newnode = (Node*)malloc(sizeof(Node));
if (NULL == newnode)
{
perror("malloc failed");
exit(-1);
}
newnode->val = x;
newnode->next = NULL;
newnode->random = NULL;
return newnode;
}
struct Node* copyRandomList(struct Node* head)
{
if (NULL == head)
return NULL;
// 穿插复制
struct Node* cur = head;
while (cur)
{
struct Node* newnode = BuyNode(cur->val);
newnode->next = cur->next;
cur->next = newnode;
cur = newnode->next;
}
// 处理random
cur = head;
while (cur)
{
if (cur->random)
cur->next->random = cur->random->next;
cur = cur->next->next;
}
// 拆开
cur = head;
struct Node* copyhead = head->next;
struct Node* copy = copyhead;
while (1)
{
cur->next = copy->next;
cur = cur->next;
if (NULL == cur)
{
copy->next = NULL;
break;
}
copy->next = cur->next;
copy = copy->next;
}
return copyhead;
}