当前位置:网站首页>[C题目]力扣138. 复制带随机指针的链表
[C题目]力扣138. 复制带随机指针的链表
2022-08-02 20:33:00 【GLC8866】
题目要求: 给你一个链表A,其中结点的next用于连接前后结点,random指向当前链表A任意结点位置或者是NULL,此时需要你再创建一个相同结构的链表B,链表B与链表A长度一样、对应位置结点的val值一样、每个结点的random指向当前链表的第几个结点也一样。
思路:在链表A的每一个结点cur后面插入一个新的结点copy,cur的random指向为cur->random,而copy的random指向为cur->random->next时就能拷贝出相同的结构。当cur->next指向NULL时为特殊情况,copy->random直接指向NULL即可。
struct Node* copyRandomList(struct Node* head)
{
//在旧链表中的每一个结点后插入新结点
struct Node* cur=head;
while(cur)
{
//创建新结点copy
struct Node* copy=(struct Node*)malloc(sizeof(struct Node));
copy->val=cur->val;
//将新结点插入cur结点的后面
copy->next=cur->next;
cur->next=copy;
//换下一个cur,直到为NULL后不再插入新结点。
cur=copy->next;
}
//新结点复制前一个结点对应的random指向结构
//与cur相对应的结点为cur->next
cur=head;
while(cur)
{
struct Node* copy=cur->next;
//random为NULL不满足复制的规律
if(cur->random==NULL)
{
copy->random=NULL;
}
else
{
copy->random=cur->random->next;
}
//换下一个cur,直到为NULL不再对cur->next进行复制random结构。
cur=copy->next;
}
//拆解链表
cur=head;
//创建哨兵位头结点copyhead,并且初始时copyhead->next必须为NULL。
struct Node* copyhead=(struct Node*)malloc(sizeof(struct Node));
copyhead->next=NULL;
//尾结点初始时为copyhead。
struct Node* copytail=copyhead;
//将每一个cur->next拆解下来尾插到copytail后面,直到cur为止。
while(cur)
{
//用copy标记cur->next。
struct Node* copy=cur->next;
//将copy尾插到copytail后面。
copytail->next=copy;
//尾结点copytail更新。
copytail=copytail->next;
//下一个cur连接上前一个cur
cur->next=copy->next;
//对下一个cur进行判断
cur=cur->next;
}
return copyhead->next;
}
边栏推荐
- DataGrip 安装教程 详细版
- The five classification of software testing
- Li Mu hands-on deep learning V2-BERT pre-training and code implementation
- 浅议.NET遗留应用改造
- "Weekly Translate Go" This time we have something different!-- "How to Code in Go" series launched
- pytorch的tensor创建和操作记录
- 【SLAM】DM-VIO(ros版)安装和论文解读
- .NET性能优化-你应该为集合类型设置初始大小
- C# Monitor类
- VisualStudio 制作Dynamic Link Library动态链接库文件
猜你喜欢

Day35 LeetCode

iframe------------frame-

OP-5,输入/输出信号范围-一信号处理能力

Flink Yarn Per Job - 启动AM

WPF development through practical 】 【 automatic production management platform

DataGrip 安装教程 详细版

Informatics orsay a tong (1258: 【 9.2 】 digital pyramid)

Li Mu hands-on learning deep learning V2-bert and code implementation

YOLOv5+BiSeNet——同时进行目标检测和语义分割

信息学奥赛一本通(1258:【例9.2】数字金字塔)
随机推荐
如何使用windbg查看C#某个线程的栈大小 ?
2022年金九银十,Android面试中高频必问的问题汇总
A brief discussion on the transformation of .NET legacy applications
.NET性能优化-你应该为集合类型设置初始大小
性能测试 - 理论
"Weekly Translate Go" This time we have something different!-- "How to Code in Go" series launched
【3D视觉】深度摄像头与3D重建
golang源码分析:time/rate
华为设备配置BFD多跳检测
Async的线程池使用的哪个?
力扣每日一题-第46天-344. 反转字符串
golang源码分析之geoip2-golang
C#异步和多线程
有效解决MySQL报错:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: NO/YES)
Likou Question of the Day - Day 46 - 344. Reverse Strings
10 种最佳 IDE 软件 ,你更忠爱哪一个?
YOLOv5+BiSeNet——同时进行目标检测和语义分割
【流媒体】推流与拉流简介
Axure9的元件用法
Helm基础知识

