leetcode-138-复制带随机指针的链表

Posted oldby

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-138-复制带随机指针的链表相关的知识,希望对你有一定的参考价值。

题目描述:

技术图片

 

方法一:回溯 O(N) O(N)

"""
# Definition for a Node.
class Node:
    def __init__(self, val, next, random):
        self.val = val
        self.next = next
        self.random = random
"""
class Solution:
    def __init__(self):
        self.dic = 
    def copyRandomList(self, head: Node) -> Node:
        if not head:
            return None
        elif head in self.dic:
            return self.dic[head]
        node_ = Node(head.val,None,None)
        self.dic[head] = node_
        node_.next = self.copyRandomList(head.next)
        node_.random = self.copyRandomList(head.random)
        
        return self.dic[head]#node

 方法二:迭代 O(n) O(N)

class Solution:
    def __init__(self):
        self.visited = 
    def getClonedNode(self,node):
        if node: 
            if node in self.visited: 
                return self.visited[node] 
            else: 
                self.visited[node] = Node(node.val, None, None) 
                return self.visited[node]
        return None

    def copyRandomList(self, head: Node) -> Node:
        if not head: 
            return head 
        old_node = head 
        new_node = Node(old_node.val, None, None) 
        self.visited[old_node] = new_node 
        while old_node != None:
            new_node.random = self.getClonedNode(old_node.random) 
            new_node.next = self.getClonedNode(old_node.next) 
            old_node = old_node.next 
            new_node = new_node.next 
        return self.visited[head]

 

方法三:迭代O(n)O(1)

"""
# Definition for a Node.
class Node:
    def __init__(self, val, next, random):
        self.val = val
        self.next = next
        self.random = random
"""
class Solution:
    def copyRandomList(self, head: Node) -> Node:
        if not head: 
            return head 
        ptr = head
        while ptr: 
            new_node = Node(ptr.val, None, None) 
            new_node.next = ptr.next 
            ptr.next = new_node 
            ptr = new_node.next 
        ptr = head 
        while ptr: 
            ptr.next.random = ptr.random.next if ptr.random else None 
            ptr = ptr.next.next 
        ptr_old_list = head # A->B->C 
        ptr_new_list = head.next # A‘->B‘->C‘ 
        head_old = head.next 
        while ptr_old_list:
            ptr_old_list.next = ptr_old_list.next.next 
            ptr_new_list.next = ptr_new_list.next.next if ptr_new_list.next else None 
            ptr_old_list = ptr_old_list.next 
            ptr_new_list = ptr_new_list.next 
        return head_old

 

以上是关于leetcode-138-复制带随机指针的链表的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]138复制带随机指针的链表

leetcode138. 复制带随机指针的链表

leetcode-138-复制带随机指针的链表

leetcode 138. 复制带随机指针的链表

LeetCode 138. 复制带随机指针的链表(Map,复制链表,Java)

LeetCode 138. 复制带随机指针的链表c++/java详细题解