题解 | #复杂链表的复制#

复杂链表的复制

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

全部评论

相关推荐

不愿透露姓名的神秘牛友
10-05 10:13
已编辑
HHHHaos:让这些老登来现在秋招一下,简历都过不去
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务