题解 | #复杂链表的复制#
复杂链表的复制
http://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
哈希表法
遍历原链表,将每一个节点各作为键,新建的待拷贝节点作为值,建立哈希表。遍历哈希表,根据键节点的next和random指针指向,将值节点之间的对应关系连接起来,实现链表拷贝。
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
if pHead == None: return None
p = pHead
# 建立哈希表
dic = {}
while pHead:
newNode = RandomListNode(pHead.label)
# 原节点作为键,新建节点作为值
dic[pHead] = newNode
pHead = pHead.next
# 连接节点
for i in dic.keys():
# 这里不清楚dic[i.next]为什么编译不通过?
dic[i].next = dic.get(i.next)
dic[i].random = dic.get(i.random)
return dic.get(p)