【leetCode138】复制带随机指针的链表

作者:日出等日落

专栏:leetCode刷题训练

                只有一条路不能选择—那就是放弃的路;只有一条路不能拒绝—那就是成长的路。

【leetCode138】复制带随机指针的链表_第1张图片

今天我来讲一下力扣138题. 复制带随机指针的链表

138. 复制带随机指针的链表 - 力扣(Leetcode)

 

目录

题目: 

第一步: 

代码展示: 

第二步:

代码展示: 

第三步:

 代码展示:

运行测试:


 

题目: 

【leetCode138】复制带随机指针的链表_第2张图片

 

 【leetCode138】复制带随机指针的链表_第3张图片

这道题解法分为三个步骤:

  1. 在原结点的基础上再拷贝一份结点,每一个结点和原来的结点一样连接到一起
  2. 设置拷贝结点的random值
  3. 拷贝结点解下去,并链接组成新的链表,最后将原结点恢复

第一步: 

【leetCode138】复制带随机指针的链表_第4张图片

 

代码展示: 

struct Node* cur=head;
    while(cur)
    {
        struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
        struct Node* next = cur->next;
        copy->val = cur->val;
        //插入
        cur->next = copy;
        copy->next = next;
        cur = next;
    }

第二步:

【leetCode138】复制带随机指针的链表_第5张图片

 

代码展示: 

 cur = head;
    while(cur)
    {
        struct Node* copy = cur->next;
        //struct Node* next = copy->next;
        if(cur->random == NULL)
        {
            copy->random = NULL;
        }
        else
        {
            copy->random = cur->random->next;
        }
        cur=cur->next->next;
    }

第三步:

【leetCode138】复制带随机指针的链表_第6张图片

 代码展示:

 cur= head;
    struct Node* newhead = NULL , *newtail =NULL;
    while(cur)
    {
        struct Node* copy = cur->next;
        struct Node* next = copy->next;
        cur->next = next;
        if(newtail == NULL)
        {
            newhead = newtail = copy;
        }
        else
        {
            newtail->next = copy;
            newtail = newtail->next;
        }
        cur = next;
    }
    return newhead;
}

运行测试:

【leetCode138】复制带随机指针的链表_第7张图片

 

你可能感兴趣的:(leetCode刷题,链表,数据结构)