复杂带有随机指针的单链表

简介:

@[TOC]

题目

力扣链接:

image-20211112160326801

思路

image-20211112163211784

代码

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */
struct Node* newnode()
{
struct Node*node=(struct Node*)malloc(sizeof(struct Node));
if(node==NULL)
{
return NULL;
}
return node;
}

struct Node* copyRandomList(struct Node* head) {
   //在复制链表时,copy结点很容易。
   //但是对random指针,需要知道原链表random的指向结点在链表中的 相对位置,以便copy结点中random的指向新的结点。
   //如果遍历原链表,去找相对位置,时间复杂度0(N^2)
   //相复杂的原因是:我们把2个链表分开看了。
   //如果我们把copy的结点插入原链表就可以极大解决相对位置问题。
   //针对相对位置,插入到原链表中,更好
    if(head==NULL)
    {
        return NULL;
    }
struct Node*cur=head;    
while(cur!=NULL)//插入到原链表
{
struct Node*tmp=cur->next;
struct Node*node=newnode();
node->val=cur->val;
cur->next=node;
node->next=tmp;
cur=tmp;
}
cur=head;
while(cur!=NULL)//修改copy的random
{
struct Node*tmp=cur->next;
if(cur->random==NULL)
{
    tmp->random=NULL;
}else
{

    tmp->random=cur->random->next;
}
cur=tmp->next;
}
struct Node*copyhead=head->next;
struct Node*copynode=copyhead;
while(copynode->next!=NULL)//提取copy的结点
{
    struct Node*tmp=copynode->next->next;
    copynode->next=tmp;
    copynode=tmp;
}
return copyhead;
}

总结

接触新的方法,思考吸收!!!!
相关文章
|
10月前
【链表OJ 11】复制带随机指针的链表
【链表OJ 11】复制带随机指针的链表
|
3月前
|
存储 C语言
用指针处理链表
用指针处理链表
35 3
|
3月前
|
存储 缓存 搜索推荐
指针链表
指针链表
23 0
|
C语言 索引
LeetCode——138. 复制带随机指针的链表
✅<1>主页:我的代码爱吃辣 📃<2>知识讲解:常见的动态内存的错误,以及柔性数组(C99) 🔥<3>创作者:我的代码爱吃辣。 ☂️<4>开发环境:Visual Studio 2022 💬<5>前言:今天带大家来看一下一道经典的链表的笔试题—— 复制带随机指针的链表,难度中等。
|
9月前
[Leetcode]138. 复制带随机指针的链表
[Leetcode]138. 复制带随机指针的链表
|
11月前
|
C++
LeetCode 138.复制带随机指针的链表
LeetCode 138.复制带随机指针的链表
35 0
|
算法 C语言 C++
【链表】Leetcode 138. 复制带随机指针的链表
这题虽然为中等难度,但找到方法后,考察的也仅是链表的增删查改四种操作。
51 0
|
C++ 索引
【LeetCode】 复制带随机指针的链表
【LeetCode】 复制带随机指针的链表
53 0
复制带随机指针的复杂链表
复制带随机指针的复杂链表
【leetCode138】复制带随机指针的链表
【leetCode138】复制带随机指针的链表