138. 随机链表的复制

自己做

解:哈希表
/*
// 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) {Node p = head;Node res = new Node(0);Node q = res;List<Node> list = new ArrayList();Map<Node, Integer> hash1 = new HashMap();int i = 0;//根据next复制链表while(p != null){q.next = new Node(p.val);q = q.next;hash1.put(p, i);list.add(q);p = p.next;i++;}//建立randomp = head;q = res.next;while(p != null){if(p.random != null)q.random = list.get(hash1.get(p.random));elseq.random = null;p = p.next;q = q.next;}return res.next;}
}
