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

Posted johnsonxiong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

 

以上是关于[LeetCode] 138. Copy List with Random Pointer_Medium tag: Linked List的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 138. Copy List with random pointer

LeetCode-138-Copy List with Random Pointer

Leetcode 138. Copy List with Random Pointer

LeetCode 138. Copy List with Random Pointer

[LeetCode] 138. Copy List with Random Pointer

leetcode 138. Copy List with Random Pointer ----- java