复杂带有随机指针的单链表

文章目录

题目

力扣链接:

image-20211112160326801

思路

image-20211112163211784

代码

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */
struct Node* newnode()
{
    
    
struct Node*node=(struct Node*)malloc(sizeof(struct Node));
if(node==NULL)
{
    
    
return NULL;
}
return node;
}

struct Node* copyRandomList(struct Node* head) {
    
    
   //在复制链表时,copy结点很容易。
   //但是对random指针,需要知道原链表random的指向结点在链表中的 相对位置,以便copy结点中random的指向新的结点。
   //如果遍历原链表,去找相对位置,时间复杂度0(N^2)
   //相复杂的原因是:我们把2个链表分开看了。
   //如果我们把copy的结点插入原链表就可以极大解决相对位置问题。
   //针对相对位置,插入到原链表中,更好
    if(head==NULL)
    {
    
    
        return NULL;
    }
struct Node*cur=head;	
while(cur!=NULL)//插入到原链表
{
    
    
struct Node*tmp=cur->next;
struct Node*node=newnode();
node->val=cur->val;
cur->next=node;
node->next=tmp;
cur=tmp;
}
cur=head;
while(cur!=NULL)//修改copy的random
{
    
    
struct Node*tmp=cur->next;
if(cur->random==NULL)
{
    
    
    tmp->random=NULL;
}else
{
    
    

    tmp->random=cur->random->next;
}
cur=tmp->next;
}
struct Node*copyhead=head->next;
struct Node*copynode=copyhead;
while(copynode->next!=NULL)//提取copy的结点
{
    
    
    struct Node*tmp=copynode->next->next;
    copynode->next=tmp;
    copynode=tmp;
}
return copyhead;
}

总结

接触新的方法,思考吸收!!!

猜你喜欢

转载自blog.csdn.net/qq_55439426/article/details/121291072