一、题目内容

image.png
image.png

二、题解

解法1:

思路

hashmap字典,遍历存储。

代码

  1. class Solution {
  2. public Node copyRandomList(Node head) {
  3. if (head == null) {
  4. return head;
  5. }
  6. HashMap<Node, Node> dicMap = new HashMap<Node, Node>();
  7. Node curr = head;
  8. while (curr != null) {
  9. dicMap.put(curr, new Node(curr.val));
  10. curr = curr.next;
  11. }
  12. curr = head;
  13. while (curr != null) {
  14. dicMap.get(curr).next = dicMap.get(curr.next);
  15. dicMap.get(curr).random = dicMap.get(curr.random);
  16. curr = curr.next;
  17. }
  18. return dicMap.get(head);
  19. }
  20. }

解法2:

思路

hashMap字典,递归存储。

代码

  1. class Solution {
  2. private HashMap<Node, Node> dicMap = new HashMap<Node, Node>();
  3. public Node copyRandomList(Node head) {
  4. if (head == null) {
  5. return head;
  6. }
  7. if (dicMap.containsKey(head)) {
  8. return dicMap.get(head);
  9. }
  10. Node node = new Node(head.val);
  11. dicMap.put(head, node);
  12. node.next = copyRandomList(head.next);
  13. node.random = copyRandomList(head.random);
  14. return node;
  15. }
  16. }