classSolution:# Two PointersdefreverseList(self,head:ListNode)->ListNode:cur,pre=head,Nonewhilecur:tmp=cur.next# 暂存后继节点 cur.nextcur.next=pre# 修改 next 引用指向pre=cur# pre 暂存 curcur=tmp# cur 访问下一节点returnpre
classNode:def__init__(self,x:int,next:'Node'=None,random:'Node'=None):self.val=int(x)self.next=nextself.random=randomclassSolution:defcopyRandomList(self,head:'Node')->'Node':ifnothead:returnheadnode_dict={}cur=head# Traverse the origin nodes and put them in a dictionarywhilecur:# Mapping the original node to a new node# Only val is updated herenode_dict[cur]=Node(x=cur.val)cur=cur.nextnode_dict[cur]=None# Traverse the dictionary and update the next and random pointercur=headwhilecur:node_dict[cur].next=node_dict[cur.next]node_dict[cur].random=node_dict[cur.random]cur=cur.next# Return the head of the new linked listreturnnode_dict[head]
Explanation
Steps
Use a dictionary to record the position of the original nodes
Update the next and random pointer in reference to the original nodes