LeetCode 138: 复制带随机指针的链表
解题思路
解题思路是使用哈希表,分为两步来进行深拷贝。
- 第一遍遍历: 创建新节点并存储在哈希表中,同时建立原链表节点到新链表节点的映射。
- 第二遍遍历: 再次遍历原链表,更新新链表节点的
next
和random
指针,根据哈希表找到对应的新节点。
代码实现
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
if(head == null) {return head;}
Node current = head;
Map<Node, Node> map = new HashMap<>();
while(current != null) {
map.put(current, new Node(current.val));
current = current.next;
}
current = head;
while(current != null) {
map.get(current).next = map.get(current.next);
map.get(current).random = map.get(current.random);
current = current.next;
}
return map.get(head);
}
}