LeetCode--No.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.

 

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.
/*
// 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 null;
        if (map.containsKey(head)){
            return map.get(head);
        }
        
        Node node = new Node(head.val, null, null);
        map.put(head, node);
        node.next = copyRandomList(head.next);
        node.random = copyRandomList(head.random);
        return node;
    }
}

一開始沒有想到遞歸. 以後拿到題還是要先想一下,遞歸能不能做,dp能不能做,然後再去想常規解法。
非遞歸的解法也沒有看,今天好累,就不看了。以後有機會再見的話。

最近不是很開心,希望早日度過這兩個月。一個人地鐵,一個人吃飯,一個人刷題,也有點習慣了。至少不會無聊。
以後想要堅持每週六參加那個leetcode的競賽。加油~!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章