zoukankan      html  css  js  c++  java
  • 力扣——Copy List with Random Pointer(复制带随机指针的链表) python实现

    题目描述:

    中文:

    给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

    要求返回这个链表的深拷贝。

    示例:

    输入:
    {"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}

    解释:
    节点 1 的值是 1,它的下一个指针和随机指针都指向节点 2 。
    节点 2 的值是 2,它的下一个指针指向 null,随机指针指向它自己。

    提示:

    你必须返回给定头的拷贝作为对克隆列表的引用。

    英文:

    Return a deep copy of the list.

    Input:
    {"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}

    Explanation:
    Node 1's value is 1, both of its next and random pointer points to Node 2.
    Node 2's value is 2, its next pointer points to null and its random pointer points to itself.

    Note:

    You must return the copy of the given head as a reference to the cloned list.

    """
    # Definition for a Node.
    class Node(object):
        def __init__(self, val, next, random):
            self.val = val
            self.next = next
            self.random = random
    """
    class Solution(object):
        def copyRandomList(self, head):
            """
            :type head: Node
            :rtype: Node
            """
            nodeDict = dict()
            dummy = Node(0, None, None)
            nodeDict[head] = dummy
            newHead, pointer = dummy, head
            while pointer:
                node = Node(pointer.val, pointer.next, None)
                nodeDict[pointer] = node
                newHead.next = node
                newHead, pointer = newHead.next, pointer.next
            pointer = head
            while pointer:
                if pointer.random:
                    nodeDict[pointer].random = nodeDict[pointer.random]
                pointer = pointer.next
            return dummy.next

    题目来源:力扣

  • 相关阅读:
    关于TCP中对于ACK报文是否需要确认的理解
    定时器
    几个错误
    C++继承与组合
    Ubuntu18的Redis: 4.0安装
    Ubuntu18.04:MySQL: 5.7安装与卸载并配置远程登录(服务器装Mysql5.7一条龙服务)
    Ubuntu18服务器修改字体大小
    Ubuntu修改系统时间
    Ubuntu18.04防火墙安装关闭开启操作等
    Ubuntu阿里云镜像源配置
  • 原文地址:https://www.cnblogs.com/spp666/p/11656483.html
Copyright © 2011-2022 走看看