天天看點

138. Copy List with Random Pointer (not do it by myself)

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.

Approach #1: Java.

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    HashMap<RandomListNode, RandomListNode> visitedHash = new HashMap<RandomListNode, RandomListNode>();
    
    public RandomListNode copyRandomList(RandomListNode head) {
        if (head == null)
            return null;
        
        if (this.visitedHash.containsKey(head))
            return this.visitedHash.get(head);
        
        
        RandomListNode node = new RandomListNode(head.label);
        
        this.visitedHash.put(head, node);
        
        node.next = this.copyRandomList(head.next);
        node.random = this.copyRandomList(head.random);
        
        return node;
    }
}
      

  

Approach #2: Python.

# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None

class Solution(object):
    def __init__(self):
        self.visited = {}
        
    def getClonedNode(self, node):
        if node:
            if node in self.visited:
                return self.visited[node]
            else:
                self.visited[node] = RandomListNode(node.label)
                return self.visited[node]
        return None
        
    def copyRandomList(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """
        if not head:
            return head
        
        old_node = head
        
        new_node = RandomListNode(old_node.label)
        self.visited[old_node] = new_node
        
        while old_node != None:
            new_node.random = self.getClonedNode(old_node.random)
            new_node.next = self.getClonedNode(old_node.next)
            
            old_node = old_node.next
            new_node = new_node.next
            
        return self.visited[head]

            
      

永遠渴望,大智若愚(stay hungry, stay foolish)