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

    题目来源:力扣

  • 相关阅读:
    研究显示:众多网上零售商未遵循Web优化基本准则
    坚果云开发团队分享高效代码审查经验
    不应忽视的HTML优化
    开源网络分析工具TCP Traffic Analyzer
    Web 2.0应用客户端性能问题十大根源
    W3C宣布成立Web性能工作组
    Google C++规范
    Yahoo推出开源YUI跨浏览器测试工具Yeti
    比较牛的一个字符画
    python调用windows下的应用程序的方法
  • 原文地址:https://www.cnblogs.com/spp666/p/11656483.html
Copyright © 2011-2022 走看看