题目入口:复杂链表的复制https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
我需要遍历一遍,用map把所有的node的val值存下来(val需要存在一个新的节点),下一次遍历的时候,可在之前创建的新节点上添加next和random.
class Solution { public Node copyRandomList(Node head) { Node cur = head; if(cur == null) return null; Map<Node,Node> map = new HashMap<>(); while(cur != null){ map.put(cur,new Node(cur.val)); cur = cur.next; } cur = head; while(cur != null){ map.get(cur).next = map.get(cur.next); map.get(cur).random = map.get(cur.random); cur = cur.next; } return map.get(head); } }