输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
重点:
- 注意深拷贝和浅拷贝的区别 浅拷贝复制索引就可以,深拷贝要拿到这个节点值重新创建一个节点,并且保证新节点的random和next和源节点一样
- 所以无论使用那种方法在对random进行链接的时候要先判断是否存在,存在的话拿random出来的节点创建一个新结点
- 一切链表的问题都可以用列表解决,
思路一:借助copy库
# -*- coding:utf-8 -*-
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
import copy
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
return copy.deepcopy(pHead)
思路二:借助列表
# -*- 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
if not pHead:
return None
nodeList = []
randomNode = []
nodePointer = pHead
while nodePointer:
tmpNode = RandomListNode(nodePointer.label)
nodeList.append(tmpNode)
if nodePointer.random:
tmpRandom = RandomListNode(nodePointer.random.label)
randomNode.append(tmpRandom)
else:
randomNode.append(None)
nodePointer = nodePointer.next
for i in range(len(nodeList)-1):
nodeList[i].next = nodeList[i+1]
nodeList[i].random = randomNode[i]
nodeList[-1].random = randomNode[-1]
ret = nodeList[0]
return ret
思路三:
# -*- 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
if pHead == None:
return None
res = RandomListNode(0)
firstNode = res
while pHead != None:
temp = RandomListNode(pHead.label)
res.label = temp.label
if pHead.random != None:
res.random = RandomListNode(pHead.random.label)
else:
res.random = None
if pHead.next != None:
res.next = RandomListNode(pHead.next.label)
else:
res.next = None
res = res.next
pHead = pHead.next
return firstNode