代码
# -*- coding:utf-8 -*-
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
self.CloneNodes(pHead)
self.ConnectSiblingNodes(pHead)
return self.ReconnectNodes(pHead)
def CloneNodes(self, pHead):
pNode = pHead
while pNode:
pCloned = RandomListNode(pNode.label)
pCloned.next = pNode.next
pCloned.random = None
pNode.next = pCloned
pNode = pCloned.next
def ConnectSiblingNodes(self, pHead):
pNode = pHead
while pNode:
pCloned = pNode.next
if pNode.random:
pCloned.random = pNode.random.next
pNode = pCloned.next
def ReconnectNodes(self, pHead):
pNode = pHead
pClonedHead = None
pClonedNode = None
if pNode:
pClonedHead = pClonedNode = pNode.next
pNode.next = pClonedNode.next
pNode = pNode.next
while pNode:
pClonedNode.next = pNode.next
pClonedNode = pClonedNode.next
pNode.next = pClonedNode.next
pNode = pNode.next
return pClonedHead