题目:
题目分析:
解决这个问题的思路如下:
1、先复制原来链表的每个节点,新节点连接起来;
2、算原链表中每个节点cur的random跟cur的相对距离,再去复制新链表到当前节点相对距离的节点,赋值给random,找每个节点的random时间复杂度是O(N),那么有N节点,整体的复杂度是O(N^2)。
这个算法的效率是比较低的,因此要对其做些优化:
1、在原链表的每个结点的后面,链接插入一个拷贝节点;
2、置random;
3、把拷贝节点解下来,链接到一起,同时恢复原链表。
代码实现:
/**
* 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;
//1.拷贝节点挂在原节点的后面
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;
}
//2.置random
cur = head;
while(cur)
{
struct Node* copy = cur->next;
if(cur->random)
copy->random = cur->random->next;
else
copy->random = NULL;
cur = copy->next;
}
//3.把原链表的节点解下来,尾插到新链表
struct Node* copyhead,*copytail;
copyhead = copytail = (struct Node*)malloc(sizeof(struct Node));
cur = head;
while(cur)
{
struct Node* copy = cur->next;
struct Node* next = copy->next;
copytail->next = copy;
copytail = copy;
cur->next = next;
cur = next;
}
struct Node* del = copyhead;
copyhead = copyhead->next;
free(del);
return copyhead;
}