当前位置:网站首页>[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;
}
边栏推荐
- Use the TCP protocol, we won't lost package?
- 你是几星测试/开发程序员?技术型选手王大拿......
- golang source code analysis: uber-go/ratelimit
- 模糊查询like用法实例(Bee)
- Packages and packages, access modifiers
- WPF development through practical 】 【 automatic production management platform
- 一款免费的容器安全 SaaS 平台使用记录
- iframe------------frame-
- js如何获取浏览器缩放比例
- 力扣每日一题-第46天-344. 反转字符串
猜你喜欢
Digital twins help visualize the construction of smart cities
HCIP--BGP基础实验
【流媒体】推流与拉流简介
"A daily practice, happy water problem" 1374. Generate a string with an odd number of each character
.NET如何快速比较两个byte数组是否相等
接口测试常用工具及测试方法(入门篇)
VisualStudio 制作Dynamic Link Library动态链接库文件
封装和包、访问修饰权限
信息系统项目管理师必背核心考点(五十八)变更管理的主要角色
2022年金九银十,Android面试中高频必问的问题汇总
随机推荐
李沐动手学深度学习V2-bert预训练数据集和代码实现
.NET如何快速比较两个byte数组是否相等
模糊查询like用法实例(Bee)
go——垃圾回收机制(GC)
用户之声 | GBASE南大通用实训有感
Which thread pool does Async use?
EasyExcel dynamic parsing and save table columns
Informatics orsay a tong (1258: 【 9.2 】 digital pyramid)
Digital twins help visualize the construction of smart cities
56.【全局变量和局部变量专题】
《分布式微服务电商》专题(一)-项目简介
How the sensor works
力扣每日一题-第46天-344. 反转字符串
YOLOv5+BiSeNet——同时进行目标检测和语义分割
Day35 LeetCode
Use the TCP protocol, we won't lost package?
C# Monitor类
setup syntax sugar defineProps defineEmits defineExpose
pytorch的tensor创建和操作记录
The software testing process specification is what?Specific what to do?