四种语言刷算法之复制带随机指针的链表

力扣138. 复制带随机指针的链表

1、C

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */
struct hashTable{
    struct Node *key,*val;
    UT_hash_handle hh;
} *cachedNode;
struct Node* copyRandomList(struct Node* head) {
    if(head==NULL)return NULL;
    struct hashTable* tmp;
    HASH_FIND_INT(cachedNode,&head,tmp);
    if(tmp==NULL){
       struct Node* newHead = (struct Node*)malloc(sizeof(struct Node));
       newHead->val = head->val;
       tmp = (struct hashTable*)malloc(sizeof(struct hashTable));
       tmp->key = head;
       tmp->val = newHead;
       HASH_ADD_INT(cachedNode,key,tmp);
       newHead->next = copyRandomList(head->next);
       newHead->random = copyRandomList(head->random);
       }
    return tmp->val;
}

2、C++

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/
class Solution {
public:
    unordered_map<Node*, Node*> cachedNode;
    Node* copyRandomList(Node* head) {
    
    if(head==NULL){
        return NULL;
    }
    if(!cachedNode.count(head)){
        Node* newHead = new Node(head->val);
        cachedNode[head] = newHead;
        newHead->next = copyRandomList(head->next);
        newHead->random = copyRandomList(head->random);   
    }
    return cachedNode[head];
    }
};

3、JAVA

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

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/
class Solution {
    Map<Node, Node> cachedNode = new HashMap<Node, Node>();
    public Node copyRandomList(Node head) {
        if(head==null)return null;
        if(!cachedNode.containsKey(head)){
            Node newNode = new Node(head.val);
            cachedNode.put(head,newNode);
            newNode.next = copyRandomList(head.next);
            newNode.random = copyRandomList(head.random);
        }
        return cachedNode.get(head);
    }
}

4、Python

"""
# Definition for a Node.
class Node:
    def __init__(self, x, next=None, random=None):
        self.val = int(x)
        self.next = next
        self.random = random
"""
class Solution(object):
    def __init__(self):
        self.cachedNode = {}
    def copyRandomList(self, head):
        """
        :type head: Node
        :rtype: Node
        """
        if head is None:
            return None
        if self.cachedNode.get(head) is None:
            newNode = Node(head.val)
            self.cachedNode[head] = newNode
            newNode.next = self.copyRandomList(head.next)
            newNode.random = self.copyRandomList(head.random)
        return self.cachedNode.get(head)
posted @ 2023-05-04 22:53  菜鸟冲冲冲  阅读(14)  评论(0)    收藏  举报