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

    题目来源:力扣

  • 相关阅读:
    idea 快捷键
    python 之网页解析器
    python 之正则表达式
    Python Requests快速入门
    Html style="visibility:hidden"与style="display:none"的区别
    html 之table标签结构学习
    python 之format字符串格式化
    Python 时间戳和日期相互转换
    SQL 字符串函数
    xampp默认配置拿shell
  • 原文地址:https://www.cnblogs.com/spp666/p/11656483.html
Copyright © 2011-2022 走看看