题解 | #复杂链表的复制#
复杂链表的复制
https://www.nowcoder.com/creation/write/md?entryPage=htthttps://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&tqId=23254&ru=/exam/oj/ta&qru=/ta/coding-interviews/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D13%26type%3D13ps%3A%2F%2Fwww.nowcoder.com%2Fpractice%2Ff836b2c43afc4b35ad6adc41ec941dba%3FtpId%3D13%26tqId%3D23254%26ru%3D%2Fexam%2Foj%2Fta%26qru%3D%2Fta%2Fcoding-interviews%2Fquestion-ranking%26sourceUrl%3D%252Fexam%252Foj%252Fta%253Fpage%253D1%2526tpId%253D13%2526type%253D13&type=0&qurl=%2Fpractice%2Ff836b2c43afc4b35ad6adc41ec941dba
# -*- 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
#定义哈希表,用原链表的节点作为键,新拷贝的链表节点做为值
Mydict = {}
newPhead = RandomListNode(-1)
pre = newPhead
cur = pHead
#拷贝旧链表
while cur:
clone = RandomListNode(cur.label)
Mydict[cur] = clone
#用尾插法将旧链表链接起来
pre.next = clone
pre = pre.next
cur = cur.next
#遍历哈希表,找到存在random的节点,把它的节点的值对应的拷贝的节点赋值过去
for (key, value) in Mydict.items():
if not key.random:
value.random = None
else:
value.random = Mydict[key.random]
return newPhead.next

查看7道真题和解析