138. Copy List with Random Pointer [Medium] 链表

138. Copy List with Random Pointer

138. Copy List with Random Pointer [Medium] 链表_第1张图片
138. Copy List with Random Pointer
"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, next, random):
        self.val = val
        self.next = next
        self.random = random

"""
class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: Node
        :rtype: Node
        """
        if head == None:
            return None
        head = self.copyNode(head)
        head = self.copyRandom(head)
        return self.split(head)
    def copyNode(self, head):
        p = head
        while p:
            node = Node(p.val, None, None)
            node.next = p.next
            p.next = node
            p = node.next
        return head
    def copyRandom(self, head):
        p = head
        while p:
            if p.random:
                p.next.random = p.random.next
            p = p.next.next
        return head
    def split(self, head):
        p = head
        res = q = head.next
        while p:
            p.next = q.next
            p = p.next
            if p:
                q.next = p.next
                q = q.next
        return res

你可能感兴趣的:(138. Copy List with Random Pointer [Medium] 链表)