首页 > 其他 > 详细

[leetcode]138. Copy List with Random Pointer复制带随机指针的链表

时间:2019-07-03 09:25:53      阅读:97      评论:0      收藏:0      [点我收藏+]

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 }

 

[leetcode]138. Copy List with Random Pointer复制带随机指针的链表

原文:https://www.cnblogs.com/liuliu5151/p/11124141.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!