138. Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

分析:

这题的关键其实是如何copy random pointer,找到一个random pointer指向的node, time complexity is O(n). 所以总的复杂度在O(n^2).

这里有一个比较巧妙的方法。在每个Node后面添加一个Node,新node的值和前一个Node一样。这样的话random pointer就很容易copy了,

利用hashmap保存original和copy

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4     int val;
 5     Node next;
 6     Node random;
 7 
 8     public Node(int val) {
 9         this.val = val;
10         this.next = null;
11         this.random = null;
12     }
13 }
14 */
15 
16 class Solution {
17     public Node copyRandomList(Node head) {
18         if (head == null) return null;
19         Map<Node, Node> map = new HashMap<>();
20         Node current = head;
21         while(current != null) {
22             map.put(current, new Node(current.val));
23             current = current.next;
24         }         
25         Node firstNode = head;
26         while(head != null) {
27             Node temp = map.get(head);
28             temp.next = map.get(head.next);
29             if(head.random != null) {
30                 temp.random = map.get(head.random);
31             }
32             head = head.next;
33         }
34         return map.get(firstNode);
35     }
36 }

 

 

转载请注明出处:cnblogs.com/beiyeqingteng/

posted @ 2016-07-03 06:55  北叶青藤  阅读(171)  评论(0编辑  收藏  举报