请实现函数复制一个复杂链表。
在复杂链表中,每个节点除了有一个指针指向下一个节点,还有一个指针指向链表中的任意节点或者None。
在不用辅助空间的情况下实现O(n)的时间效率。分为三步:根据原始链表的每个节点创建对应的新节点、设置复制出来的节点的random、把这个长链表拆分成两个链表。
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
def copy_complex_list(self, head):
if not head or not head.next:
return head
self.clone_nodes(head)
self.connect_sibling_nodes(head)
return self.reconnect_nodes(head)
def clone_nodes(self, head):
p = head
while p:
q = RandomListNode(p.label)
q.next = p.next
p.next = q
p = q.next
def connect_sibling_nodes(self, head):
p = head
while p:
q = p.next
if p.random:
q.random = p.random.next
p = q.next
def reconnect_nodes(self, head):
p = head
if p:
clone_head = p.next
q = clone_head
p.next = q.next
p = p.next
while p:
q.next = p.next
q = q.next
p.next = q.next
p = p.next
return clone_head
st = Solution()
node = RandomListNode(1)
node.next = RandomListNode(2)
node.next.next = RandomListNode(3)
node.next.next.next = RandomListNode(4)
node.next.next.next.next = RandomListNode(5)
node.random = node.next.next
node.next.random = node.next.next.next.next
node.next.next.next.random = node.next
head = st.copy_complex_list(node)
while head:
if head.random:
print(head.label, head.random.label)
else:
print(head.label)
head = head.next
(最近更新:2019年07月24日)
本文介绍了一种在O(n)时间复杂度内且不使用额外空间复制复杂链表的方法。复杂链表中,每个节点除了指向下一个节点外,还指向链表中的任意节点或None。文章详细描述了通过三个步骤实现复制:创建节点副本、设置随机指针和拆分链表。
2108

被折叠的 条评论
为什么被折叠?



