一、题目内容

二、题解
解法1:
思路
hashmap字典,遍历存储。
代码
class Solution { public Node copyRandomList(Node head) { if (head == null) { return head; } HashMap<Node, Node> dicMap = new HashMap<Node, Node>(); Node curr = head; while (curr != null) { dicMap.put(curr, new Node(curr.val)); curr = curr.next; } curr = head; while (curr != null) { dicMap.get(curr).next = dicMap.get(curr.next); dicMap.get(curr).random = dicMap.get(curr.random); curr = curr.next; } return dicMap.get(head); }}
解法2:
思路
hashMap字典,递归存储。
代码
class Solution { private HashMap<Node, Node> dicMap = new HashMap<Node, Node>(); public Node copyRandomList(Node head) { if (head == null) { return head; } if (dicMap.containsKey(head)) { return dicMap.get(head); } Node node = new Node(head.val); dicMap.put(head, node); node.next = copyRandomList(head.next); node.random = copyRandomList(head.random); return node; }}