1: 题意
深拷贝一个链表,同时要把每个链表的random指针也要指向新的链表的对应的节点
首先我们先解决一个简单的问题就是如何深拷贝一个最普通的链表
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
## 生拷贝
head2 = Node(head.val)
cur = head.next
cur2 = head2
while cur!= None:
cur2.next = Node(cur.val)
cur = cur.next
cur2 = cur2.next
return head2
然后思考我们怎么把random弄到对的链表,我们可以用map记录一下每个链表节点对应的新的链表节点是哪个,然后我们再次遍历原链表然后我们再赋值random
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
## 生拷贝
if head == None: return None
head2 = Node(head.val)
cur = head.next
cur2 = head2
map = {head : head2}
while cur!= None:
newNode = Node(cur.val)
map [cur] = newNode
cur2.next = newNode
cur = cur.next
cur2 = cur2.next
print(1)
cur = head
cur2 = head2
while cur != None:
random1 = cur.random
if random1 != None:
cur2.random = map[random1]
cur = cur.next
cur2 = cur2.next
return head2
时间复杂度: O(n)
空间复杂度:O (n)
优化:
这个思路非常巧妙,就是我们先直接在原链表复制一个节点放在源节点后面
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
if head is None:
return None
cur = head
while cur:
cur.next = Node(cur.val, cur.next)
cur = cur.next.next
cur = head
while cur:
if cur.random:
cur.next.random = cur.random.next
cur = cur.next.next
cur = head.next
while cur.next:
cur.next = cur.next.next
cur = cur.next
return head.next