zoukankan      html  css  js  c++  java
  • 剑指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
                
  • 相关阅读:
    typescript泛型
    安卓手机IPhone抓包Https
    js里面for循环的++i与i++
    http请求头
    从浏览器地址栏输入url到页面呈现
    docker部署nodejs应用
    mac下使用MongoDB
    使用vue-cli3&vue ui图形化界面创建项目
    javascript中的call, apply(转载)
    跨域请求
  • 原文地址:https://www.cnblogs.com/wangzhihang/p/11796247.html
Copyright © 2011-2022 走看看