Friday, September 12, 2014

Leetcode: Copy List with Random Pointer @Python

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

class Solution:
    # @param head, a RandomListNode
    # @return a RandomListNode
    def copyRandomList(self, head):
        if not head: return None
        keephead=head
        while head:
            crt=RandomListNode(head.label)
            crt.next=head.next
            head.next=crt
            head=crt.next
        head=keephead
        while head:
            crt=head.next
            if head.random:
                crt.random=head.random.next
            head=crt.next
        newhead=keephead.next
        head=keephead
        while head:
            crt=head.next
            head.next=crt.next
            if crt.next:
                crt.next=crt.next.next
            head=head.next
        return newhead

No comments :

Post a Comment