码迷,mamicode.com
首页 > 其他好文 > 详细

138. Copy List with Random Pointer

时间:2017-07-24 18:53:27      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:ict   val   http   nic   targe   self   hat   span   ons   

https://leetcode.com/problems/copy-list-with-random-pointer/#/description

 

 

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.

 

 

Sol 1:

 

# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None

class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """
        # Time O(2n) Space O(1) 

        dic = dict()
        m = n = head
        
        # m is to copy label data structure, one pass. Time O(n) 
        while m:
            dic[m] = RandomListNode(m.label)
            m = m.next
        # n is to copy next and random data structure. one pass. Time O(n)
        while n:
            dic[n].next = dic.get(n.next)
            dic[n].random = dic.get(n.random)
            n = n.next
        return dic.get(head)

 

 

Note:

 

1 In the initlization of a linked list, 

 

self.label = x

 

"label" here mean value.... it‘s a name, does not matter

 

 

 

 

 

 

Sol 2:

 

# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None

import collections
class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """
        # Time O(n) Space O(1) 

        # Nice lambda initlization here. Pythonic
        dic = collections.defaultdict(lambda : RandomListNode(0))
        dic[None] = None
        
        n = head

        while n:
            dic[n].label = n.label
            dic[n].next = dic[n.next]
            dic[n].random = dic[n.random]
            n = n.next
        return dic.get(head)

 

138. Copy List with Random Pointer

标签:ict   val   http   nic   targe   self   hat   span   ons   

原文地址:http://www.cnblogs.com/prmlab/p/7230192.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!