面试题35. 复杂链表的复制
思路:
class Solution {
public Node copyRandomList(Node head) {
//建立指针cur,指向head
Node cur = head;
//新建HashMap
HashMap<Node, Node> map = new HashMap<>();
//当cur指向不为空
while (cur != null) {
//往hashmap中添加原链表cur指向的节点,以及新链表对应的值
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);
}
}