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++实现贴在后面,

转载于:https://www.cnblogs.com/joelwang/p/10322016.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值