LeetCode:138. 随机链表的复制之如何有效copy

 自己复制的话,很容易写出来一个时间复杂度O(n ^ 2) 空O(n)的做法

我们可以参考基因的复制,

目录

题目:

实现思路(基因复制式的copy):

官方快慢指针解法:时O(n)空O(1)

 博主的 时O(n ^ 2) 空O(n)刺眼代码:

每日表情包:


题目:

LeetCode:138. 随机链表的复制之如何有效copy_第1张图片

快慢指针实现思路(基因复制式的copy):

                1,创建结点:我们插入式的给每个结点的后面创建我们的新链表的结点(后续会把创建的结点抠出来)

                2,赋值:我们根据(模仿)创建的新结点的复制对象,易知我们copy的新结点的。random指针指向的就是复制对象的random指针所指向的结点的下一个结点。

                3,把copy的结点抠出来,

(细节,注意random可能指向NULL),如果看不懂可以去看视频力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

官方快慢指针解法:时O(n)空O(1)

struct Node* copyRandomList(struct Node* head) {
    if (head == NULL) {
        return NULL;
    }
    for (struct Node* node = head; node != NULL; node = node->next->next) {
        struct Node* nodeNew = malloc(sizeof(struct Node));
        nodeNew->val = node->val;
        nodeNew->next = node->next;
        node->next = nodeNew;
    }
    for (struct Node* node = head; node != NULL; node = node->next->next) {
        struct Node* nodeNew = node->next;
        nodeNew->random = (node->random != NULL) ? node->random->next : NULL;
    }
    struct Node* headNew = head->next;
    for (struct Node* node = head; node != NULL; node = node->next) {
        struct Node* nodeNew = node->next;
        node->next = node->next->next;
        nodeNew->next = (nodeNew->next != NULL) ? nodeNew->next->next : NULL;
    }
    return headNew;
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/copy-list-with-random-pointer/solutions/889166/fu-zhi-dai-sui-ji-zhi-zhen-de-lian-biao-rblsf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 博主的 时O(n ^ 2) 空O(n)刺眼代码:

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */
struct Node* BuyNode()
{
    struct Node* ptmp = (struct Node*)malloc(sizeof(struct Node));
    //assert(ptmp);
    ptmp->next = NULL;
    return ptmp;
}
struct Node* copyRandomList(struct Node* head) {
    //sentry head 没动
	struct Node* Sentry = BuyNode();//sentry哨兵
    //assert(Sentry);
    struct Node* pcur = head, * pfr = head;//pfr == pFindRandom
    struct Node* pNewTmp = Sentry;
    //新链表
    while(pcur){
        pNewTmp->next = BuyNode();
        pNewTmp = pNewTmp->next;
        pNewTmp->val = pcur->val;
        pcur = pcur->next;
    }
    //处理random
    struct Node* pNewCur = Sentry->next;
    pcur = head;
    while(pNewCur){
        //找对应节点
        pfr = head;
        pNewTmp = Sentry->next;
        while(pcur->random != pfr){
            pfr = pfr->next;
            pNewTmp = pNewTmp->next;
        }
        //赋值random
        pNewCur->random = pNewTmp;
        //next结点
        pNewCur = pNewCur->next;
        pcur = pcur->next;
    }
    //free(sentry);
    return Sentry->next;
}

每日表情包:

LeetCode:138. 随机链表的复制之如何有效copy_第2张图片

我王小桃想要赞!

你可能感兴趣的:(leetcode,链表,算法)