描述
给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。
您在真实的面试中是否遇到过这个题?
挑战
可否使用O(1)的空间
这一题有点意思,若是不考虑只用O(1)的空间的话,有点像图的深拷贝那一题,用hashmap解决,具体可以看:https://blog.csdn.net/wenqiwenqi123/article/details/79997684
当然这一题的挑战是可否使用o(1)的空间,那就要想想办法了。请注意的是这里的O(1)空间指的是额外空间,拷贝的那条链表耗费的空间是不算的。
具体方法看我代码中注释:
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# @param head: A RandomListNode
# @return: A RandomListNode
def copyRandomList(self, head):
#输入1->2->3->None
#则中间结果为1->1(copy)->2->2(copy)->3->3(copy)->None
#返回1(copy)->2(copy)->3(copy)->none
save=head
#构造中间链表
while(head!=None):
new=RandomListNode(head.label)
new.next=head.next
head.next=new
head=new.next
#取得random指针
head=save
while(head!=None):
if(head.random!=None):
head.next.random=head.random.next
else: head.next.random=None
head=head.next.next
head=save.next
#取得最终链表
while(head!=None):
if(head.next==None):
head.next=None
break
else:
head.next=head.next.next
head=head.next
return save.next
node1 = RandomListNode(1)
# node2 = RandomListNode(2)
# node1.next = node2
s = Solution()
result = s.copyRandomList(node1)
while (result != None):
print(result.label)
result = result.next