leetcode 138. Copy List with Random Pointer复杂链表的复制

时间:2021-10-27 15:51:59

leetcode 138. Copy List with Random Pointer复杂链表的复制

leetcode 138. Copy List with Random Pointer复杂链表的复制

python代码如下:

 # Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if not head:
return None
#复制节点本身
cur=head
while cur:
clone=RandomListNode(cur.label)
nextNode=cur.next
cur.next=clone
clone.next=nextNode
cur=nextNode
#复制随机指针
cur=head
while cur:
if cur.random:
cur.next.random=cur.random.next
else:
cur.next.random=None
cur=cur.next.next
#拆开
cur=head
pClone=head.next
while cur:
clone=cur.next
cur.next=clone.next
if clone.next:
clone.next=clone.next.next
else:clone.next=None
cur=cur.next
return pClone

因为一开始没看明白题目所以直接看答案了,发现原来就是插入链表节点再把链表拆开,python代码为粘贴自别人,下次用C++实现贴在后面,