[LeetCode] 138. Copy List with Random Pointer_Medium tag: Linked List

这个题目有两种做法,

note: 注意head.random有可能是None的情况

1. S: O(n)    create一个dictionary,然后先建dictionary和copy list以及next指针。然后再一遍,去建random指针。

2: S: O(1)    利用如下图所示的结构,然后再将copy node和原来的node分开即可。

Old List: A --> B --> C --> D
InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D'

1. code S:O(n)
class Node:
    def __init__(self, x, next, random):
        self.val = x
        self.next = next
        self.random = random

class Solution:
    def deepCopyList(self, head):
        dummy, listMap = Node(0, None, None), dict()
        head1, head2 = head, dummy
        # copy the list and next pointers
        while head1:
            head2.next = Node(head1.val, None, None)
            ListMap[head1] = head2.next
            head1 = head1.next
            head2 = head2.next
        # copy the random pointers
        head1, head2 = head, dummy.next
        while head1:
            if head1.random: # head1.random can be None
                head2.random = listMap[head1.random]
            head1 = head1.next
            head2 = head2.next
        return dummy.next

2. code     S: O(1)

def deepCopyList(self, head):
    dummy = Node(0, None, None)
    dummy.next = head
    # make copy nodes
    while head:
        temp = head.next
        head.next = Node(head.val, None, None)
        head.next.next = temp
        head = temp
    # create random pointers
    head = dummy.next
    while head:
        if head.random:
            head.next.random = head.random.next
        head = head.next.next
    # make copy list and recover the original list
    dummy2 = Node(0, None, None)
    head1, head2 = dummy.next, dummy2
    while head1:
        head2.next = head1.next
        head1.next= head1.next.next
        head1 = head1.next
        head2 = head2.next
    return dummy2.next

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/10807771.html