题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
输入输出示例
解题思路
- 考虑空的情况
- 首先复制链表中一样的结点,并添加到旧链表的相同链表结点的后面
- 实现新建的每个node的random指向
- 断开新旧两个链表的连接,并返回新链表的首节点
代码示例
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
# 考虑为空的情况
if pHead == None:
return None
#复制一个一样的node,并且添加到之前的链表的每个node之后
temp = pHead
while temp:
node = RandomListNode(temp.label)
node.next = temp.next
temp.next = node
temp = node.next
# 实现新建的node的random的指向
temp = pHead
while temp:
if temp.random:
temp.next.random = temp.random.next
temp = temp.next.next
# 断开原来的node和新的复制的node直接的连接
temp = pHead # 旧链表的指针
new_temp = pHead.next #复制新的链表的指针
newHead = pHead.next #最终要返回的新链表的首节点
while temp:
temp.next = temp.next.next
if new_temp.next:
new_temp.next = new_temp.next.next
new_temp = new_temp.next
temp = temp.next
return newHead
if __name__ == '__main__':
node1 = RandomListNode(1)
node2 = RandomListNode(2)
node3 = RandomListNode(3)
node4 = RandomListNode(4)
node5 = RandomListNode(5)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = None
s = Solution()
newHead = s.Clone(node1)
temp = newHead
while temp:
print(temp.label)
temp = temp.next
递归方法
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if pHead == None:
return None
newHead= RandomListNode(pHead.label)
newHead.random = pHead.random
newHead.next = self.Clone(pHead.next)
return newHead