当前位置:网站首页>【力扣】复制带随机指针的链表
【力扣】复制带随机指针的链表
2022-07-17 05:13:00 【Patrick star`】
138. 复制带随机指针的链表 - 力扣(LeetCode)
题目:
给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。
构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
思路:
代码:
struct Node* copyRandomList(struct Node* head)
{
struct Node* cur = head;
struct Node* copyHead = NULL;
if(head == NULL)//原链表为空链表
{
return copyHead;
}
while(cur)
{
struct Node* copyNode = (struct Node*)malloc(sizeof(struct Node));
copyNode->val = cur->val;
copyNode->next = cur->next;
cur->next = copyNode;
cur = cur->next->next;
}
copyHead = head->next;
cur = head;
while(cur)
{
if(cur->random)
{
cur->next->random = cur->random->next;
}
else
{
cur->next->random = NULL;
}
cur = cur->next->next;
}
struct Node* temp = NULL;
cur = copyHead;
while(cur->next)
{
temp = cur->next->next;
cur->next = temp;
cur = temp;
}
return copyHead;
}
边栏推荐
- Wireless charging mouse pad RGB LED lighting wireless charging mouse pad
- MEX and Increments
- 2022/07/12 学习笔记 (day05)循环
- 4路编码器脉冲计数器,8路DO,Modbus TCP模块
- 串口循环缓存区 简单 免初始化 不用堆、指针、分段memcpy
- Configure the 'log' shortcut key in vscode and remove the console log(‘‘); Semicolon in;
- Darwin 反射总结
- Fs5383a lithium battery 3.7V input power supply solar lawn lamp drive IC
- 简单Chrome脚本 自动跳过b站视频播放结束后的的充电鸣谢页面
- [USACO06DEC]The Fewest Coins G(混合背包)
猜你喜欢
DSL实现自动补全查询
Configure the 'log' shortcut key in vscode and remove the console log(‘‘); Semicolon in;
ES聚合分析报错:“reason“ : “Text fields are not optimised for operations
MySQL Workbench基本使用【创建一个数据库】
Chrome浏览器设置 【显示右上角 翻译语言图标】
Fs4061a (5V USB input, double lithium battery series application, 5V boost charging, 8.4v Management IC
Fs68001 wireless charging SOC chip has simple periphery and schematic diagram of 5W wireless charging scheme
EasyDarawin流媒体服务器介绍
VSCode 即时英文翻译插件 【翻译(英汉词典)】
Vscode instant English translation plug-in [translation (English Chinese Dictionary)]
随机推荐
开源在线的MarkDown编辑器 --【Editor.md】
【力扣】翻转二叉树
Boost dc/dc converter
5-17陕西科技大学的隐藏学生服务
vscode 配置golang开发环境
Hra2460d-2w high voltage power supply high voltage module - high voltage - high precision hra2460d-2w
配置VsCode中‘log’快捷键去掉console.log(‘‘);中的分号;
Qtss callback routine
绝世好题(位运算优化dp)
[详细教程安装][配置] VsCode中关于Eslint的辅助插件
Chrome浏览器设置 【显示右上角 翻译语言图标】
本地makefile 编译其他文件夹文件 指定obj目录
Darwin 反射总结
[BJOI2019] 排兵布阵(分组背包)
Analog signal in-depth discussion on the transmission distance of 4-20mA current signal
4-channel encoder pulse counter, speed measurement, 8-Channel do, Modbus TCP data acquisition module
带透明png转换成c数组
DSL实现Bucket聚合
自动补全 & (自定义)拼音分词器 & 搜索时注意事项
2021-11-26 pyautogui cooperates with lightning simulator to realize the automation of mobile app check-in and answer questions