Leetcode質問138-ランダムポインタを含むリンクリストをコピーする

ここに画像の説明を挿入
ここに画像の説明を挿入
問題分析:この
問題では、リンクリストをコピーし、コピーしたリストのヘッドノードを返す必要があります。分析するために絵を描く
ここに画像の説明を挿入

アイデア:
1。図に示すように、各ノードをコピーして、元のノードの背面に接続します
ここに画像の説明を挿入

//1.拷贝节点,连接到每一个原节点的后边
 struct Node* cur = head;
	while(cur)
    {
    
    
        struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
        copy->next = NULL;
        copy->val = cur->val;
        copy->random = NULL;

        struct Node* next = cur->next;
        cur->next = copy;
        copy->next = next;
        
        cur = next;
    }

2.各ノードのランダムをコピーします。図に示すように、各コピーノードのランダムは元のノードのランダムの次のものです。
ここに画像の説明を挿入

//2.拷贝原节点中的random
    cur = head;
    while(cur)
    {
    
    
        struct Node* copy = cur->next;
        if(cur->random == NULL)
        {
    
    
            copy->random = NULL;
        }
        else
        {
    
    
            copy->random = cur->random->next;
        }
        cur = copy->next;
    }

3.コピーしたリンクリストを分割します
ここに画像の説明を挿入

while(cur)
    {
    
    
        struct Node* copy = cur->next;
        struct Node* next = copy->next;

        cur->next = next;
        if(next)
        {
    
    
            copy->next = next->next;
        }
        else
        {
    
    
            copy->next = NULL;
        }
        cur = next;
    }

完全なコードは次のとおりです。

struct Node* copyRandomList(struct Node* head) {
    
    
    if(head == NULL)
    {
    
    
        return NULL;
    }
    //1.拷贝节点,连接到每一个原节点的后边
    struct Node* cur = head;
	while(cur)
    {
    
    
        struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
        copy->next = NULL;
        copy->val = cur->val;
        copy->random = NULL;

        struct Node* next = cur->next;
        cur->next = copy;
        copy->next = next;
        
        cur = next;
    }
    //2.拷贝原节点中的random
    cur = head;
    while(cur)
    {
    
    
        struct Node* copy = cur->next;
        if(cur->random == NULL)
        {
    
    
            copy->random = NULL;
        }
        else
        {
    
    
            copy->random = cur->random->next;
        }
        cur = copy->next;
    }

    //3.拆分出复制链表
    cur = head;
    struct Node* copyHead = head->next;
    while(cur)
    {
    
    
        struct Node* copy = cur->next;
        struct Node* next = copy->next;

        cur->next = next;
        if(next)
        {
    
    
            copy->next = next->next;
        }
        else
        {
    
    
            copy->next = NULL;
        }
        cur = next;
    }
    return copyHead;
}

おすすめ

転載: blog.csdn.net/weixin_50843868/article/details/111977159