程序媛詹妮弗
终身学习

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.

 

Example 1:

Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}

Explanation:
Node 1's value is 1, both of its next and random pointer points to Node 2.
Node 2's value is 2, its next pointer points to null and its random pointer points to itself.

 

Note:

  1. You must return the copy of the given head as a reference to the cloned list.

 

题意

给定一个单链表,链表中的每个节点包含一个额外的指针,随机指向链表中的其它节点或者指向 null。请复制整个链表,并返回新链表的头结点。

思路

1、 copy nodes:HashMap存入每个 node 和 new node(deep copy后的)

2、 link  nodes: 扫一遍原链表, 将每个node的next和random关系link起来

 

 

代码

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4     public int val;
 5     public Node next;
 6     public Node random;
 7 
 8     public Node() {}
 9 
10     public Node(int _val,Node _next,Node _random) {
11         val = _val;
12         next = _next;
13         random = _random;
14     }
15 };
16 */
17 class Solution {
18       public Node copyRandomList(Node head) {
19         if (head == null) return null;
20 
21         Map<Node, Node> map = new HashMap<>();
22 
23         //copy all the nodes
24         Node node = head;
25         while (node != null) {
26             map.put(node, new Node(node.val, node.next, node.random));
27             node = node.next;
28         }
29 
30         // assign next and random pointers
31         node = head;
32         while (node != null) {
33             map.get(node).next = map.get(node.next);
34             map.get(node).random = map.get(node.random);
35             node = node.next;
36         }
37 
38         return map.get(head);
39     }
40 }

 

posted on 2019-07-03 05:26  程序媛詹妮弗  阅读(204)  评论(0编辑  收藏  举报