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

    题目来源:力扣

  • 相关阅读:
    Mysql技术内幕——InnoDB存储引擎
    Nginx 0.7.x + PHP 5.2.6(FastCGI)+ MySQL 5.1 在128M小内存VPS服务器上的配置优化
    Mysql5.5 InnoDB存储引擎配置和优化
    MySQL存储引擎总结
    MySQL存储引擎--MyISAM与InnoDB区别
    MySQL存储引擎
    Mysql的建表规范与注意事项
    安装好oracle11gR2之后在相应路径下却没有生成tnsnames.ora和listener.ora
    split切割.号的字符串
    配置文件c3p0-config.xml
  • 原文地址:https://www.cnblogs.com/spp666/p/11656483.html
Copyright © 2011-2022 走看看