美文网首页
[LeetCode 138] Copy List with Ra

[LeetCode 138] Copy List with Ra

作者: 灰睛眼蓝 | 来源:发表于2019-06-13 15:01 被阅读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:

    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:[LeetCode 138] Copy List with Ra

          本文链接:https://www.haomeiwen.com/subject/rglsfctx.html