• 25、复杂链表的复制


    输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

    =================Python=================

    # -*- 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
            def dfs(pHead):
                if pHead is None:
                    return
                if pHead in visited:
                    return visited[pHead]
                node = RandomListNode(pHead.label)
                visited[pHead] = node
                node.next = dfs(pHead.next)
                node.random = dfs(pHead.random)
                return node
            visited = {}
            return dfs(pHead)

    ================Java================

    /*
    public class RandomListNode {
        int label;
        RandomListNode next = null;
        RandomListNode random = null;
    
        RandomListNode(int label) {
            this.label = label;
        }
    }
    */
    public class Solution {
        public RandomListNode Clone(RandomListNode pHead)
        {
            HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
            RandomListNode cur = pHead;
            while (cur != null) {
                map.put(cur, new RandomListNode(cur.label));
                cur = cur.next;
            }
            
            cur = pHead;
            while (cur != null) {
                map.get(cur).next = map.get(cur.next);
                map.get(cur).random = map.get(cur.random);
                cur = cur.next;
            }
            return map.get(pHead);
        }
    }
  • 相关阅读:
    Linux实时性分析-schedule-调度器
    中断解析
    网络商城-PrestaShop
    和学生的学习互动记录(10嵌)
    QQ记录
    Windows7硬盘安装Fedora16图文教程
    今目标登录时报网络错误E110
    vs环境配置——vs快捷键配置——vs插件配置——vs环境设置
    如何防止app接口被别人调用
    mvc4 找到多个与名为“xx”的控制器匹配的类型
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13538835.html
Copyright © 2020-2023  润新知