额。。。这一题没有做出来。。确实没有想到如何很好的处理这个问题。复制的过程中不知道要拿random这个属性怎么办。。所以只能看题解了。。。
①看别人的说法是拼接加拆分,也有叫原地修改的。。。
思想就是先不考虑random的复制,并且复制的节点就在被复制的节点前面,成为一个整体的链表,然后下一步进行random的复制,由于是整个表是连在一起的,所以找到被复制节点指向的random节点的下一个节点,就是复制节点random所指向的节点---------cur.next.random = cur.random.next;最后再对表进行拆分操作,将被复制的节点和复制的节点分开来。
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head: return
cur = head
while cur:
temp = Node(cur.val)
temp.next = cur.next
cur.next = temp
cur = temp.next
cur = head
while cur:
if cur.random:
cur.next.random = cur.random.next
cur = cur.next.next
cur = res = head.next
pre = head
while cur.next:
pre.next = pre.next.next
cur.next = cur.next.next
pre = pre.next
cur = cur.next
pre.next = None
return res
②使用哈希表的方法--------才知道python中的哈希表就是字典的意思。。。
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return
dic = {}
cur = head
# key存储被复制的节点,value存储复制后的节点(先忽略random)
while cur:
dic[cur] = Node(cur.val)
cur = cur.next
cur = head
# 每一个next和random都在字典中保留,所以直接连接就可以了
while cur:
dic[cur].next = dic.get(cur.next)
dic[cur].random = dic.get(cur.random)
cur = cur.next
return dic[head]
③又又一次看到了递归的方法- -、tql 不过这里也是同样使用字典的方法
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
node_map = {}
def Clone1(head):
if not head:
return None
node_map[head] = Node(head.val)
if head.next:
node_map[head].next = Clone1(head.next)
if head.random in node_map:
node_map[head].random = node_map[head.random]
return node_map[head]
return Clone1(head)