leetcode 【 Copy List with Random Pointer 】 python 实现

题目

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

 

代码:Runtime: 215 ms

复制代码
 1 # Definition for singly-linked list with a random pointer.
 2 # class RandomListNode:
 3 #     def __init__(self, x):
 4 #         self.label = x
 5 #         self.next = None
 6 #         self.random = None
 7 
 8 class Solution:
 9     # @param head, a RandomListNode
10     # @return a RandomListNode
11     def copyRandomList(self, head):
12         if head is None:
13             return head
14         
15         # insert newnode between every two nodes between oldlist
16         p = head
17         while p is not None:
18             newnode = RandomListNode(p.label)
19             tmp = p.next
20             p.next = newnode
21             newnode.next = tmp
22             p = tmp
23         
24         # copy random point
25         p = head
26         while p is not None:
27             if p.random is not None:
28                 p.next.random = p.random.next
29             p = p.next.next
30         
31         # extract the new list from mixed list
32         newhead = head.next
33         p = head
34         while p is not None:
35             tmp = p.next
36             p.next = p.next.next
37             p = p.next
38             if tmp.next:
39                 tmp.next = tmp.next.next
40             tmp = tmp.next
41         
42         return newhead
复制代码

 

思路

自己想不出来巧的方法 网上找个靠谱的帖子:

http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5ODIzNDQ3Mw==&appmsgid=10000291&itemidx=1&sign=ccde63918a24dee181f1fd1a4e3e6781

参照上述帖子的思路写的python代码。

遇到的一个问题是,一开始判断极端case的时候有“if head.next is None: return head”

结果一直报错,后来去掉后AC了。注意一个点的时候也要复制。

还有就是,一直对python里面变量间的赋值不太清楚,google了一篇如下的日志,讲的比较靠谱一些。

http://www.cnblogs.com/evening/archive/2012/04/11/2442788.html

posted on   承续缘  阅读(482)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示