剑指offer 35. 复杂链表的复制

题目:请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。  中等
方法一:AA'BB'CC'  时间复杂度O(n)  空间复杂度O(1)  
首先将链表ABC复制成AA'BB'CC',再设置random指针,最后断链
class Node(object):
        def __init__(self,val,next=None,random=None):
            self.val = val
            self.next = next
            self.random = random
def copyRandomList(head):
        """
        :type head: Node
        :rtype: Node
        """
        if head is None:
            return None
        
        cur = head
        while cur:
            new = Node(cur.val)
            new.next = cur.next
            cur.next = new
            cur = new.next
        
        cur = head
        while cur:
            if cur.random:
                cur.next.random = cur.random.next
            cur = cur.next.next
        
        new_head = Node(-1)
        p = new_head
        cur = head
        while cur:
            p.next = cur.next
            p = p.next
            cur.next = p.next
            cur = cur.next
        
        return new_head.next
           

 

方法二:字典  时间复杂度O(n)  空间复杂度O(n)  
将原链表的每一个节点的复制放在字典中,按照字典的索引赋指针

def copyRandomList(head):
        """
        :type head: Node
        :rtype: Node
        """
        if head is None:
            return None
        
        dic = {}
        cur = head
        while cur:
            new = Node(cur.val)
            dic[cur] = new
            cur = cur.next
        
        cur = head
        while cur:
            if cur.next:
                dic[cur].next = dic[cur.next]
            if cur.random:
                dic[cur].random = dic[cur.random]
            cur = cur.next
        
        return dic[head]

 

posted @ 2022-07-26 11:46  Liang-ml  阅读(25)  评论(0)    收藏  举报