1. 题目
题目链接138. 复制带随机指针的链表
2. 思路
使用hashmap存储旧的节点和新的节点,然后利用旧节点的指向关系去构建新的节点的指向关系。
3. 代码
/*
// 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;
// 使用map存储 然后取出来连接
Map<Node, Node> hashMap = new HashMap();
Node curr = head;
while (curr != null) {
Node node = new Node(curr.val);
hashMap.put(curr, node);
curr = curr.next;
}
// 依次取出来 然后连接
curr = head;
while (curr != null) {
hashMap.get(curr).next = hashMap.get(curr.next);
hashMap.get(curr).random = hashMap.get(curr.random);
curr = curr.next;
}
return hashMap.get(head);
}
}