示例1
输入:
{1,2,3,4,5,3,5,#,2,#}
返回值:
{1,2,3,4,5,3,5,#,2,#}
我的代码:
def findByVale(self, x):
if x == '#': return None
p = self
while p:
if p.label == x: return p
p = p.next
return None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
if pHead is None: return None
head = RandomListNode(pHead.label)
tail = head
p = pHead.next
while p:
tail.next = RandomListNode(p.label)
tail = tail.next
p = p.next
tail.next = None
tail = head
p = pHead # 注意是pHead不是head
while p:
tail.random = findByVale(head, p.random.label) if p.random else None
tail = tail.next
p = p.next
return head
投机倒把:
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
if pHead is None: return None
head = RandomListNode(-1) # 头结点
tail = head
p = pHead
while p:
tail.next = RandomListNode(p.label)
tail.next.random = p.random # random直接复用 多输出没有影响 但是并不符合题意
tail = tail.next
p = p.next
tail.next = None
return head.next
递归投机倒把
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
if not pHead: return #pHead是None 不必创建
newNode = RandomListNode(pHead.label)
newNode.random = pHead.random # 复用了 并没有完全创建新节点 不符合题意 但不影响输出
newNode.next = self.Clone(pHead.next) # 递归克隆下一个节点
return newNode