leetcode138 — 复制带随机指针的链表

题目:

在这里插入图片描述
题目链接

思路:
1. 遍历原来的链表并拷贝每一个节点,将拷贝节点放在原来节点的下一个,创造出一个旧节点和新节点交错的链表。
2. 迭代这个新旧节点交错的链表,并用旧节点的 random 指针去更新对应新节点的 random 指针。
3. random 指针已经被赋值给正确的节点, next 指针也需要被正确赋值,以便将新的节点正确链接同时将旧节点重新正确链接。

图示如下:

在这里插入图片描述在这里插入图片描述

//如果cur->random不为空,则copyNode->random 为 cur->random->next
if(cur->random)
	copyNode->random = cur->random->next;

在这里插入图片描述

//分开链接
    while(cur)
    {
        Node *copyNode = cur->next;
        Node *next = copyNode->next;
        cur->next = next;
        if(next)
            copyNode->next = next->next;
        else
            //最后一个拷贝结点的next置为NULL
            copyNode->next = NULL;
        cur = next;
    }

实现代码:

typedef struct Node Node;
struct Node* copyRandomList(struct Node* head) {
    if(head == NULL)
        return NULL;
    Node *cur = head;
    //在原链表后拷贝一份
    while(cur)
    {
        Node *copyNode = (Node *)malloc(sizeof(Node));
        copyNode->val = cur->val;
        copyNode->next = NULL;
        copyNode->random = NULL;

        Node *next = cur->next;
        copyNode->next = next;
        cur->next = copyNode;
        cur = next;
    }
    cur = head;
    //拷贝random
    while(cur)
    {
        Node *copyNode = cur->next;
        if(cur->random)
            copyNode->random = cur->random->next;
        else
            copyNode->random = NULL;
        cur = cur->next->next;
    }
  cur = head;
  Node *newnode = head->next;
    //分开链接
    while(cur)
    {
        Node *copyNode = cur->next;
        Node *next = copyNode->next;
        cur->next = next;
        if(next)
            copyNode->next = next->next;
        else
            copyNode->next = NULL;
        cur = next;
    }
	return newnode;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值