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.拷贝每一个节点的random。如图所示,每一个copy节点的random都是原节点的random的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.拆分出复制的链表
在这里插入图片描述

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