- 先用哈希表生成每个节点对应的新的节点,然后从头遍历原链表,根据next,random指针给新的链表设置next,random值。
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return
dic={}
cur=head
while cur:
dic[cur]=Node(cur.val)
cur=cur.next
cur=head
while cur:
dic[cur].next=dic.get(cur.next)
dic[cur].random=dic.get(cur.random)
cur=cur.next
return dic[head]
- 1.首先就是将链表进行一次复制,或者说,在原元素的后面,插入一个相同数值的节点 2.复制random指针.3 分离两个链表
复杂链表的复制(python) - 董不耀 - 博客园 (cnblogs.com)
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if head==None:
return None
cur = head
while cur:
tmp=Node(cur.val) #造1'
tmp.next=cur.next #造1'>2
cur.next=tmp#造1>1'
cur=cur.next.next#继续遍历1'后的元素2
cur = head
while cur and cur.next:
if cur.random: # 如果cur有random,我们再操作
cur.next.random = cur.random.next # 1的random指向7,则复制的1’的random指向7‘(即7.next)
cur = cur.next.next #继续遍历1'后的元素2
cur = head #链表1
new = head.next #链表1'
res = head.next #等着1'>2'>3'>4'这个链表的头部输出
while cur :
cur.next = cur.next.next #分离出1>2
if new.next: #先结束 因为未复制最后的none
new.next=new.next.next #分离出1'>2'
new = new.next #继续遍历1'后的元素2';
cur = cur.next #继续遍历1后的元素2;
return res