[LeetCode 138] Copy List with Random Pointer (Medium)

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:

image

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.

Solution

  1. 用HashMap来联系每个原始的节点和copy节点。
  2. 先走一遍原始list,然后一次复制,向Hashmap中放入原始和copy节点。并且把每个复制的节点next pointer连起来,random pointer先不管
  3. 再走一遍list,此时链接copy节点的random pointer
while (current != null) {
            dummy.random = originVsCopy.get (current.random);
            current = current.next;
            dummy = dummy.next;
        }

代码

/*
// Definition for a Node.
class Node {
    public int val;
    public Node next;
    public Node random;

    public Node() {}

    public Node(int _val,Node _next,Node _random) {
        val = _val;
        next = _next;
        random = _random;
    }
};
*/
class Solution {
    public Node copyRandomList(Node head) {
        if (head == null)
            return head;
        
        Map<Node, Node> originVsCopy = new HashMap<> ();
        
        Node copyDummy = new Node ();
        Node dummy = copyDummy;
        
        Node current = head;
        
        while (current != null) {
            Node newCopy = new Node (current.val, null, null);
            originVsCopy.put (current, newCopy);
            
            dummy.next = newCopy;
            current = current.next;
            dummy = dummy.next;
        }
        
        current = head;
        dummy = copyDummy.next;
        while (current != null) {
            dummy.random = originVsCopy.get (current.random);
            current = current.next;
            dummy = dummy.next;
        }
        
        return copyDummy.next;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,160评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,471评论 0 23
  • 人群中能吸引人的一定是那些特立独行或者奇装异服的人,社交场合中能吸引人眼球的也一定是那个与众不同的人,所以在瞬息...
    power女神阅读 1,722评论 0 0
  • 文|图 舒行之 北大的春天生机盎然,各色花开,争相斗艳,尤其这大朵大朵类似牡丹的花,不知道是不是牡丹,各种颜色,开...
    舒行之阅读 4,256评论 2 3
  • 不断进步。很多人的进步到30多岁就停止了,只有很少的人一直能够坚持到老年。永远要承认自己的贫穷,不用担心别人的白眼...
    StarXing2018阅读 1,313评论 0 0