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
  • 相关阅读:
    多线程的互斥(下)——信号量
    多线程间的互斥-锁(下)
    多线程间的互斥(上)
    多线程间的同步
    Qt中的多线程编程
    进程和线程的概念
    【linux Vim】8-Vim高级应用
    【linux Vim】7-Vim基本操作
    【linux Vim】6-Vim介绍
    【linux 正则表达式】5-扩展正则表达式
  • 原文地址:https://www.cnblogs.com/seyjs/p/11896057.html
Copyright © 2011-2022 走看看