题目:
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
思路:
自己想不出来巧的方法 网上找个靠谱的帖子:
参照上述帖子的思路写的python代码。
遇到的一个问题是,一开始判断极端case的时候有“if head.next is None: return head”
结果一直报错,后来去掉后AC了。注意一个点的时候也要复制。
还有就是,一直对python里面变量间的赋值不太清楚,google了一篇如下的日志,讲的比较靠谱一些。
http://www.cnblogs.com/evening/archive/2012/04/11/2442788.html
时间: 2024-12-21 17:03:15