010、随机链表复制

0、题目描述

随机链表复制

1、法1

我的第一个想法是,直接把random指针看成一个结构体成员,我创建节点的时候加一个结构体成员不就可以了吗?指针不也是一个地址数据吗?

实际上指针是具有结构特点的,如果按照我的想法复制,random是空的时候没问题,不是空的时候random指针不是指向新链表里面的结构,还是指向原来链表的结构,这条路走不通。

copy链表和原链表得先建立联系,把每一个节点复制在原节点的后面,这样的好处是:
copy链表的random,等于原链表的random的next。 如图。

复制完copy里面的random之后,再把copy链表给解下来,还原原链表。

1、拷贝到每个节点的后面,组成两倍长度的新链表

2、复制里面的random

3、解开copy链表

c 复制代码
/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */

struct Node* BuyNewNode(int val)
{
    struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
    newnode->val = val;
    newnode->next = NULL;
    newnode->random = NULL;
    return newnode;
}

struct Node* copyRandomList(struct Node* head) 
{
    if (head == NULL)
        return NULL;
	struct Node* cur = head;
    struct Node* newnode = NULL;
    struct Node* next = NULL;
    //把每个节点放在原节点的后面
    while (cur)
    {
        next = cur->next;
        newnode  = BuyNewNode(cur->val);
        cur->next = newnode;
        newnode->next = next;
        cur = next;
    }
    
    cur = head;
    struct Node* newlist = cur->next;
    struct Node* newcur = newlist;
    while (cur)
    {
        //复制节点的random,上一个节点random的next
        if (cur->random == NULL)
        {
            newcur->random = NULL;
        } 
        else
        {
            newcur->random = cur->random->next;
        }
        
        //复制完random之前不能动cur->next
        
        cur = cur->next->next;
        if (cur)
            newcur = newcur->next->next;
    }

    //解开
    cur = head;
    newcur = newlist = cur->next;
    while (cur)
    {
        cur->next = newcur->next;
        cur = cur->next;
        if (cur)
        {
            newcur->next = cur->next;
            newcur = newcur->next;
        }
    }
    return newlist;
}

这里注意newcur可能会越界,所以要 if 拦截一下,cur走到头的时候,不要让newcur再走了!

相关推荐
自然数e29 分钟前
c++多线程【多线程常见使用以及几个多线程数据结构实现】
数据结构·c++·算法·多线程
黛色正浓32 分钟前
leetCode-热题100-普通数组合集(JavaScript)
java·数据结构·算法
千金裘换酒40 分钟前
LeetCode 环形链表+升级版环形链表
算法·leetcode·链表
辞砚技术录1 小时前
MySQL面试题——索引、B+树
数据结构·数据库·b树·面试
666HZ6662 小时前
数据结构1.0 数据结构在学什么
数据结构·算法
余瑜鱼鱼鱼2 小时前
Java数据结构:从入门到精通(五)
数据结构
空空潍2 小时前
hot100-滑动窗口最大值(day11)
数据结构·c++·算法·leetcode
R-G-B2 小时前
BM28 二叉树的最大深度
数据结构·算法·二叉树·bm28·二叉树的最大深度
iAkuya2 小时前
(leetcode)力扣100 35 LRU 缓存(双向链表&哈希)
leetcode·链表·缓存
菜鸟233号3 小时前
力扣416 分割等和子串 java实现
java·数据结构·算法·leetcode