思路源于
【力扣hot100】【LeetCode 138】随机链表的复制|哈希表
采用一个哈希表,键值对为<原链表的结点,新链表的结点>,第一次遍历原链表结点时只创建新链表的结点,第二次遍历原链表结点时,通过键拿到新链表结点,新链表结点的next指向哈希表中键为原链表结点的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) {
Map<Node, Node> oldMapNew = new HashMap<>();
for (Node cur = head; cur != null; cur = cur.next) {
Node newNode = new Node(cur.val);
oldMapNew.put(cur, newNode);
}
for (Node cur = head; cur != null; cur = cur.next) {
Node newNode = oldMapNew.get(cur);
newNode.next = oldMapNew.get(cur.next);
newNode.random = oldMapNew.get(cur.random);
}
return oldMapNew.get(head);
}
}