复制带随机指针的链表.leetcode138《数据结构入门到精通N11》

简介: 复制带随机指针的链表.leetcode138《数据结构入门到精通N11》

题目链接


138. 复制带随机指针的链表 - 力扣(LeetCode) (leetcode-cn.com)


题目简介


image.png


image.png


image.png


思路


先连要复制的点在原链表上,再把random正确链接,再解除与原链表的连接并还原原链表。

/**
 * 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;
    struct Node* cur=head;
    //把要复制的链表插入原链表
    while(cur!=NULL)
    {
        struct Node* copy=(struct Node*)malloc(sizeof(struct Node));
        if(copy==NULL)
        {
            printf("malloc fail\n");
            exit(-1);
        }
        copy->next=cur->next;
        cur->next=copy;
        copy->val=cur->val;
        cur= cur->next->next;
    }
    //让newnode的random指向正确位置
    cur=head;
    struct Node* copyhead=cur->next;
    struct Node* copy=cur->next;
    while(cur)
    {
        struct Node* copy=cur->next;
        if(cur->random == NULL)
        {
            copy->random=NULL;
        }
        else
        {
            copy->random=cur->random->next;
        }
        cur=copy->next;
    }
    //拷贝节点解下来,并链接到一起
    cur=head;
    struct Node* copytail=NULL;
    copyhead=NULL;
    while(cur)
    {
        struct Node* copy=cur->next;
        struct Node* next=copy->next;
        cur->next=next;
        if(copytail==NULL)//尾插
        {
            copyhead=copytail=copy;
        }
        else
        {
            copytail->next=copy;
            copytail=copytail->next;
        }
        cur=next;
    }
    return copyhead;
}


最后的最后,创作不易,希望读者三连支持💖

赠人玫瑰,手有余香💖

相关文章
|
2天前
|
存储
数据结构链表详解(不仅顺序表可以,我链表也可以)
数据结构链表详解(不仅顺序表可以,我链表也可以)
11 0
|
4天前
|
存储
数据结构第二课 -----线性表之单向链表
数据结构第二课 -----线性表之单向链表
|
3天前
教你三指针拿捏链表翻转
教你三指针拿捏链表翻转
|
4天前
|
存储 算法 Java
数据结构与算法 数组和链表
数据结构与算法 数组和链表
12 0
|
4天前
|
存储 Java
深入浅出数据结构之链表
深入浅出数据结构之链表
|
4天前
|
C++
数据结构(双链表
数据结构(双链表
11 1
|
4天前
|
算法 测试技术 容器
【刷题】双指针入门
经过这四道题目的洗礼,我大概对双指针有了初步印象,接下来我会继续努力!!!
44 13
【刷题】双指针入门
|
4天前
|
算法 C++
【C++入门到精通】智能指针 shared_ptr循环引用 | weak_ptr 简介及C++模拟实现 [ C++入门 ]
【C++入门到精通】智能指针 shared_ptr循环引用 | weak_ptr 简介及C++模拟实现 [ C++入门 ]
15 0
|
4天前
|
安全 算法 数据安全/隐私保护
【C++入门到精通】智能指针 shared_ptr 简介及C++模拟实现 [ C++入门 ]
【C++入门到精通】智能指针 shared_ptr 简介及C++模拟实现 [ C++入门 ]
13 0
|
4天前
|
存储 算法 安全
【C++入门到精通】智能指针 auto_ptr、unique_ptr简介及C++模拟实现 [ C++入门 ]
【C++入门到精通】智能指针 auto_ptr、unique_ptr简介及C++模拟实现 [ C++入门 ]
13 0