Python AC code but I think it's wrong


  • 0
    H

    Wrote two pieces of code, both of whom are accepted. But I think one of them is WRONG. Basically, the one with comments creates a list that has duplicates of random nodes, while the other one has no duplicate. I think the former one is wrong. Did I misunderstand the problem? Or I'm just right?

    class Solution(object):
        # if I uncomment below comments it is AC too, and I think that is the correct one.
        def copyRandomList(self, head):
             dummy, current, mapping = RandomListNode(0), head, {None: None}
             prev  = dummy
             while current:
                 # if current in mapping:
                 #     node = mapping[current]
                 # else:
                 node = RandomListNode(current.label)
                 mapping[current] = node
                 if current.random in mapping:
                     node.random = mapping[current.random]
                 else:
                     node.random = RandomListNode(current.random.label)
                     # mapping[current.random]=node.random
                 prev.next, prev = node, node
                 current = current.next
             self.printList(dummy.next)
             self.printRandom(dummy.next)
             return dummy.next
    
         # these two functions are helpers to print the whole list
         def printRandom(self, head):
             while head.random:
                 print head.label, ".random->",
                 head=head.random
             while head:
                 print "->",head.label,
                 head=head.next
             print 
    
         def printList(self, head):
             while head:
                 if head.random:
                     print "(", head.label, ".random->", head.random.label, ")",
                 else:
                     print "(", head.label, ".random->null", ")",
                 if head.next:
                     print "->",
                 head=head.next
             print

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.