剑指offer复杂链表的复制python

题目描述

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

思路

用字典,把原链表的每个节点对应到新的节点,然后再扫描原节点,把特殊指针补上

代码

# -*- 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
        #扫2遍?
        if not pHead:
            return None
        #node 与 node之间映射
        nHead = RandomListNode(pHead.label)
        nCurrent = nHead
        pCurrent = pHead.next
        mapper = {}
        mapper[id(pHead)] = nHead
        mapper[id(None)] = None
        
        while pCurrent:
            node = RandomListNode(pCurrent.label)
            nCurrent.next = node
            nCurrent = nCurrent.next
            mapper[id(pCurrent)] = nCurrent
            pCurrent = pCurrent.next
        
        pCurrent = pHead
        nCurrent = nHead
        
        while pCurrent:
            nCurrent.random = mapper[id(pCurrent.random)]
            pCurrent = pCurrent.next
            nCurrent = nCurrent.next
        return nHead
            

 

posted @ 2019-11-05 08:35  小小文艺范  阅读(165)  评论(0编辑  收藏  举报

contact me

email:78910421@qq.com