LeetCode 138.复制带随机指针的链表

要求

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。要求返回这个链表的深度拷贝。

解法

例如
在这里插入图片描述
链表如下 1的random指向3,2的random指向1,3的random指向他自己,4的random指向NULL。
1.首先需要将链表的每个节点复制一下,并连接到每一个结点的后面。形成如图的新链表。
在这里插入图片描述2.将每一个新节点的random指向相应的结点上。完成如下图的操作

3.最终将这个复杂的链表分割成两个相同的链表。
在这里插入图片描述
这样就完成了这个链表的拷贝

代码

/**复杂链表的定义
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     struct RandomListNode *next;
 *     struct RandomListNode *random;
 * };
 */
typedef struct RandomListNode node;
struct RandomListNode *copyRandomList(struct RandomListNode *head) 
{
    if(head == NULL)
        return NULL;
    else
    {
        node* cur = head;
        while(cur)
        {   //复制新节点
            node* newnode = (node*)malloc(sizeof(node));
            newnode->label = cur->label;
            newnode->next = cur->next;
            cur->next = newnode;
            cur = newnode->next;  
        }
        node* t = head;
        node* Tnext =NULL;
        while(t)//将每一个新节点找到相应的random域中
        {
            if(t->random!=NULL)
            {
                Tnext = t->next;
                Tnext->random = t->random->next;
                t = Tnext->next;
                
            }
            else
            {
                Tnext = t->next;
                Tnext->random = t->random;
                t = Tnext->next;
                
            }

        }
        node* ret = head;
        node* pt = head->next;
        node* tmp = ret->next;
        while(tmp->next)//分隔两个链表
        {
            ret->next = tmp->next;
            ret = ret->next;
            tmp->next = ret->next;
            tmp = tmp->next;
        }
        ret->next =NULL;
        return pt; 
    }
    
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值