码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 【 Copy List with Random Pointer 】 python 实现

时间:2015-01-11 17:39:30      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

题目

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

leetcode 【 Copy List with Random Pointer 】 python 实现

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4216655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!