[Algo] 131. Deep Copy Linked List With Random Pointer
2024-09-27 11:31:42
Each of the nodes in the linked list has another pointer pointing to a random node in the list or null. Make a deep copy of the original list.
/**
* class RandomListNode {
* public int value;
* public RandomListNode next;
* public RandomListNode random;
* public RandomListNode(int value) {
* this.value = value;
* }
* }
*/
public class Solution {
public RandomListNode copy(RandomListNode head) {
// Write your solution here.
if (head == null) {
return head;
}
Map<RandomListNode, RandomListNode> map = new HashMap<>();
map.put(head, new RandomListNode(head.value));
RandomListNode dummy = new RandomListNode(0);
RandomListNode cur = dummy; while (head != null) {
if (!map.containsKey(head)) {
map.put(head, new RandomListNode(head.value));
}
// connect for the next of cur
cur.next = map.get(head);
if (head.random != null) {
if (!map.containsKey(head.random)) {
map.put(head.random, new RandomListNode(head.random.value));
}
cur.next.random = map.get(head.random);
}
head = head.next;
cur = cur.next;
}
return dummy.next;
}
}
最新文章
- Surface Shader简单向导
- JavaScript Patterns 2.10 Naming Conventions
- golang代码执行顺序
- docker居然需要3.10以上的内核
- Using Boost Libraries in Windows Store and Phone Applications
- Python入门,新手之路
- HDU 3932 Groundhog Build Home 【基础模拟退火】
- Java中abstract关键字详解
- Dijkstra算法 Java实现
- MongoDB与python交互
- 在React中使用Typescript的实践问题总结
- 软件测试2019:第四次作业—— 性能测试(含JMeter实验)
- 【Gym 100947I】What a Mess
- vue修饰符学习
- ado.net 中事务的使用
- Linux基础四(服务管理)
- HDU 6008 - Worried School
- 微信小程序注册身份证验证
- cocos2dx lua 图片去色shader
- Field &#39;email&#39; doesn&#39;t have a default value