Wins the Offer (Python variety of ideas to achieve): Complex copy of the list
35 interview questions:
Title: Complex copy of the list
Title: Enter a complex list (each node has a node value, and two pointers, one pointing to the next node, a special pointer to any other node), returns a value after the head of the list replication complex. (Note that the output results do not return parameter node reference, otherwise the program will return empty sentenced questions directly)
A problem-solving ideas: "Python"
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
import copy
return copy.deepcopy(pHead)
Problem-solving ideas II:
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if pHead==None:
return None
self.CloneNodes(pHead)
self.ConnectRandomNodes(pHead)
return self.ReconnectNodes(pHead)
def CloneNodes(self,pHead):
'''
复制原始链表的每个结点, 将复制的结点链接在其原始结点的后面
'''
pNode=pHead
while pNode:
pCloned=RandomListNode(0)
pCloned.label=pNode.label
pCloned.next=pNode.next
pNode.next=pCloned
pNode=pCloned.next
def ConnectRandomNodes(self,pHead):
'''
将复制后的链表中的克隆结点的random指针链接到被克隆结点random指针的后一个结点
'''
pNode=pHead
while pNode:
pCloned=pNode.next
if pNode.random!=None:
pCloned.random=pNode.random.next
pNode=pCloned.next
def ReconnectNodes(self,pHead):
'''
拆分链表:将原始链表的结点组成新的链表, 复制结点组成复制后的链表
'''
pNode=pHead
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
Solution three: recursion.
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if pHead==None:
return None
newNode=RandomListNode(pHead.label)
newNode.random=pHead.random
newNode.next=self.Clone(pHead.next)
return newNode