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

 

python代码如下:

 1 # Definition for singly-linked list with a random pointer.
 2 # class RandomListNode(object):
 3 #     def __init__(self, x):
 4 #         self.label = x
 5 #         self.next = None
 6 #         self.random = None
 7 
 8 class Solution(object):
 9     def copyRandomList(self, head):
10         """
11         :type head: RandomListNode
12         :rtype: RandomListNode
13         """
14         if not head:
15             return None
16         #复制节点本身
17         cur=head
18         while cur:
19             clone=RandomListNode(cur.label)
20             nextNode=cur.next
21             cur.next=clone
22             clone.next=nextNode
23             cur=nextNode
24         #复制随机指针
25         cur=head
26         while cur:
27             if cur.random:
28                 cur.next.random=cur.random.next
29             else:
30                     cur.next.random=None
31             cur=cur.next.next
32         #拆开
33         cur=head
34         pClone=head.next
35         while cur:
36             clone=cur.next
37             cur.next=clone.next
38             if clone.next:
39                 clone.next=clone.next.next
40             else:clone.next=None
41             cur=cur.next
42         return pClone

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

猜你喜欢

转载自www.cnblogs.com/joelwang/p/10322016.html
今日推荐