题目
开始的错误思路
1.创建新的链表(单链表)
2.在新的链表上解决random的指向
(1)cur遍历原链表,newcur遍历新链表
(2)find是找到与原链表相同 val 的地址(错误之处就在这里:假如原链表有多个相同的val就错了)
时间复杂度:O(N*N)
空间复杂度:O(N)
代码
错误的原因
没有考虑到原链表有多个相同的val的节点存在
优化思路
要求时间复杂度:O(N)
steps:
1.把建立的新节点拷贝到原节点的后面
2.新节点的random就是原节点的random的下一个节点
3.新节点链在一起形成新链表,恢复原链表
画图更好理解:
代码
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
typedef struct Node Node;
struct Node* copyRandomList(struct Node* head) {
if(head==NULL)
return NULL;
//1.把建立的新节点拷贝到原节点的后面
Node*cur=head;
Node*next=cur->next;
Node*copy;
while(cur)
{
//创建新节点
copy=(Node*)malloc(sizeof(Node));
copy->val=cur->val;
cur->next=copy;
copy->next=next;
cur=next;
if(next)
next=cur->next;
}
//2.解决random的指向 --> copy->random=cur->random->next
cur=head;
while(cur)
{
copy=cur->next;
if(cur->random==NULL)
{
copy->random=NULL;
}
else
{
copy->random=cur->random->next;
}
cur=cur->next->next;
}
//3.尾插+恢复
cur=head;
Node*newhead=NULL,*newtail=NULL;
while(cur)
{
copy=cur->next;
next=copy->next;
if(newhead==NULL)
{
newhead=newtail=copy;
}
else{
newtail->next=copy;
newtail=newtail->next;
}
cur->next=next;
cur=next;
}
return newhead;
}