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