[Lintcode]105. Copy List with Random Pointer/[Leetcode]138. Copy List with Random Pointer

105. Copy List with Random Pointer/138. Copy List with Random Pointer

  • 本题难度: Medium
  • Topic: Linked List
    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.

Challenge
Could you solve it with O(1) space?

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.

Challenge
Could you solve it with O(1) space?

别人的代码

法1

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


class Solution:
    # @param head: A RandomListNode
    # @return: A RandomListNode
    def copyRandomList(self, head):
        # write your code here
        dic = collections.defaultdict(lambda: RandomListNode(0))
        dic[None] = None
        pos = head
        while(pos):
            dic[pos].label = pos.label
            dic[pos].next = dic[pos.next]
            dic[pos].random = dic[pos.random]
            pos = pos.next
        return dic[head]

法2

def copyRandomList(self, head):
    if not head:
        return None
    p = head
    while p:
        node = RandomListNode(p.label)
        node.next = p.next
        p.next = node
        p = p.next.next
        # p = node.next
    p = head    
    while p:
        if p.random:
            p.next.random = p.random.next
        p = p.next.next
    newhead = head.next
    pold = head
    pnew = newhead
    while pnew.next:
        pold.next = pnew.next
        pold = pold.next
        pnew.next = pold.next
        pnew = pnew.next
    pold.next = None
    pnew.next = None
    return newhead

思路
没太理解深拷贝的意思。后来看了一下,应该是要完全拷贝数据(包括原有的数据结构)。即使原有的数据删除了,不影响返回的结果。
实在没思路,参考了别人的代码。
法1: 用dictionary的话,可以在O(n)时间内,一次遍历。next和random的指针,先用一个RandomListNode(0)占位,等遍历到该点时,再补全。
法2: 不用dictionary。比较复杂。用了很多技巧

  • 时间复杂度
  • 出错
posted @ 2019-02-14 16:51  siriusli  阅读(118)  评论(0编辑  收藏  举报