Leetcode "Copy List with Random Pointer" Python implementation

Source: Internet
Author: User

title :

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

Return a deep copy of the list.

Code : runtime:215 ms

1 #Definition for singly-linked list with a random pointer.2 #class Randomlistnode:3 #def __init__ (self, x):4 #Self.label = x5 #Self.next = None6 #self.random = None7 8 classSolution:9     #@param head, a randomlistnodeTen     #@return a Randomlistnode One     defcopyrandomlist (Self, head): A         ifHead isNone: -             returnHead -          the         #Insert newnode between every, nodes between Oldlist -p =Head -          whileP is  notNone: -NewNode =Randomlistnode (P.label) +TMP =P.next -P.next =NewNode +Newnode.next =tmp Ap =tmp at          -         #copy Random Point -p =Head -          whileP is  notNone: -             ifP.random is  notNone: -P.next.random =P.random.next inp =P.next.next -          to         #extract the new list from mixed list +Newhead =Head.next -p =Head the          whileP is  notNone: *TMP =P.next $P.next =P.next.nextPanax Notoginsengp =P.next -             ifTmp.next: theTmp.next =Tmp.next.next +TMP =Tmp.next A          the         returnNewhead

Ideas :

I can not think of a clever way to find a reliable online post:

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

The Python code is written with the idea of the above post.

One problem is that "if Head.next is None:return head" when judging extreme cases at first

Results have been error, and then removed after the AC. Pay attention to a point when you want to copy it.

There is, has been the python inside the variable assignment is not very clear, Google has a log below, speaking more reliable.

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

Leetcode "Copy List with Random Pointer" Python implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.