zoukankan      html  css  js  c++  java
  • 【leetcode】138. Copy List with Random Pointer

    题目如下:

    A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

    Return a deep copy of the list.

    Example 1:

    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:

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

    解题思路:我的方法是先深拷贝list及其next,同时把新旧两个list的每个元素浅拷贝都存起来放到两个数组中;第二次再遍历旧的list,根据random找到对应item在数组中的下标,再把新的list中同一个item指向数组中对应的下标的元素即可。

    代码如下:

    """
    # 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
            """
            list1 = []
            list2 = []
            new_head = None
            current = None
            old_head = head
            while old_head is not None:
                if new_head == None:
                    new_head = Node(old_head.val,None,None)
                    current = new_head
                else:
                    new_node = Node(old_head.val,None,None)
                    current.next = new_node
                    current = current.next
                list1.append(old_head)
                list2.append(current)
                old_head = old_head.next
    
            old_head = head
            current = new_head
            while old_head is not None:
                if old_head.random is not None:
                    inx = list1.index(old_head.random)
                    current.random = list2[inx]
                old_head = old_head.next
                current = current.next
            return new_head
  • 相关阅读:
    webkit浏览器常见开发问题
    解密H264、AAC硬件解码的关键扩展数据处理
    Bitmap那些事之内存占用计算和加载注意事项
    android apk 防止反编译技术第三篇-加密
    linux设备驱动第五篇:驱动中的并发与竟态
    如何简单快速调试高大上的谷歌浏览器
    Asp.net Mvc对比Php的4大误解
    Python初学记录
    SQL循环+游标
    Nico Game Studio 3.地图纹理编辑 物体皮肤编辑
  • 原文地址:https://www.cnblogs.com/seyjs/p/11896057.html
Copyright © 2011-2022 走看看