1. 程式人生 > >[leetcode]138. Copy List with Random Pointer

[leetcode]138. Copy List with Random Pointer

138. Copy List with Random Pointer

方法一 Complexity O(n), Space O(n)

做一箇舊結點和新結點的對映,再連線 random 指向的舊結點的對映結點

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

class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """
        res = RandomListNode(0)
        p = head

        dic = {}

        while p:
            dic[p] = RandomListNode(p.label)
            p = p.next

        p = head
        q = res

        while p:
            q.next = dic[p]
            q = q.next

            # q.next = dic[p.next]
            if p.random:
                q.random = dic[p.random]

            p = p.next

        return res.next

方法二 Complexity O(n), Space O(1)

使用舊連結串列儲存新結點的先後關係,同時也能儲存 random 指標的相對關係。

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

class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """
        
        p = head
        
        # add new node following origin node
        # Old List: A --> B --> C --> D
        # InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D'
        while p:
            new_node = RandomListNode(p.label)
            p.next, new_node.next = new_node, p.next
            p = new_node.next
        
        
        # allocate random pointer for new node
        p = head
        pre = RandomListNode(0)
        q = pre
        while p:
            q = p.next
            if p.random:
                q.random = p.random.next
            p = q.next
        
        
        # split the origin node and new node
        p = head
        q = pre
        while p:
            q.next = p.next
            q = q.next
            p.next = q.next
            p = p.next
        
        return pre.next