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
  • 相关阅读:
    jquery $.each遍历json数组方法
    JQuery插件编写
    创建JAVASCRIPT对象3种方法
    微信开发流程
    有关索引那点事
    获取数据库内所有的表和表内字段的信息
    asp.net MVC4 异步文件上传
    QT学习:01 工程文件详解
    QT学习:00 介绍
    Linux 系统编程 学习 总结
  • 原文地址:https://www.cnblogs.com/seyjs/p/11896057.html
Copyright © 2011-2022 走看看