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

    题目来源:力扣

  • 相关阅读:
    11、MyBatis教程之动态SQL
    10、MyBatis教程之一对多处理
    9、MyBatis教程之多对一处理
    8、MyBatis之使用注解开发
    7、MyBatis教程之分页实现
    6、MyBatis教程之日志实现
    5、MyBatis教程之ResultMap
    4、MyBatis教程之配置解析
    3、MyBatis教程之CURD操作
    Session的几种保存方式
  • 原文地址:https://www.cnblogs.com/spp666/p/11656483.html
Copyright © 2011-2022 走看看