【leetcode 138. 复制带随机指针的链表】解题报告
2024-10-22 09:40:12
方法一:递归
unordered_map<Node*,Node*> dict;
Node* copyRandomList(Node* head) {
if (!head) return head;
if (dict.count(head)) return dict[head];
dict[head]=new Node(head->val, nullptr, nullptr);
dict[head]->next=copyRandomList(head->next);
dict[head]->random=copyRandomList(head->random);
return dict[head];
}
方法二:非递归
Node* copyRandomList(Node* head)
{
if (!head) return head;
unordered_map<Node*,Node*> m;
Node *p=head;
while(p) // make a copy of nodes
{
m[p]=new Node(p->val,nullptr,nullptr);
p=p->next;
}
p=head;
while(p) // link everyone and fill the random field
{
m[p]->next=m[p->next];
m[p]->random=m[p->random];
p=p->next;
}
return m[head];
}
最新文章
- win7的svchost.exe占用内存过高如何解决
- Android--ColorMatrix改变图片颜色
- 兼容IE与firefox的css 线性渐变(linear-gradient)
- 人脸识别的ppt
- 空格&;amp;nbsp在不同浏览器中显示距离不一致问题解决方法
- 【POJ 1330 Nearest Common Ancestors】LCA问题 Tarjan算法
- SQL Server 后续去除功能汇总
- Ubuntu tty中文字符乱码
- 【Python】debug工具-pdb(转)
- Spring Boot2.1.3全局跨域
- Django_简单的数据库交互案例
- kali源更新
- [转]每天一个linux命令(44):top命令
- django 有关session内部函数做法
- Matlab绘图添加直角坐标轴
- 【MyBatis】解析MyBatis传入参数的问题
- Laravel基础
- 使用Java Servlet进行简单登录
- python itertools模块练习
- SUSE Linux忘记root密码的对策