Lintcode-copy List with Random Pointer

Source: Internet
Author: User
Tags lintcode

Lintcode-copy List with Random Pointer

    • Lintcode-copy List with Random Pointer
      • Web Link
      • Description
      • Code-c
      • Tips

Web Link

http://www.lintcode.com/en/problem/copy-list-with-random-pointer/

Description

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.
-Challenge
Could you Solve it with O (1) space?

Code-c++
/** * Definition for singly-linked list with a random pointer. * struct RANDOMLISTNODE {* int label; * Random ListNode *next, *random; * Randomlistnode (int x): label (x), Next (null), random (null) {} *}; */Class Solution { Public:/** * @param head:the head of linked list with a random pointer.     * @return: A new head of a deep copy of the list. */    voidCopynext (Randomlistnode*Head) { while(Head!= NULL) {Randomlistnode*NewNode= NewRandomlistnode (head -label); NewNode -Random=Head -Random NewNode -Next=Head -Next Head -Next=NewNode; Head=Head -Next -Next }    }voidCopyrandom (Randomlistnode*Head) { while(Head!= NULL) {if(Head -Next -Random!= NULL) {Head -Next -Random=Head -Random -Next } head=Head -Next -Next }} Randomlistnode*Splitlist (Randomlistnode*Head) {Randomlistnode*Newhead=Head -Next while(Head!= NULL) {Randomlistnode*Temp=Head -Next Head -Next=Temp -Next Head=Head -Nextif(Temp -Next!= NULL) {Temp -Next=Head -Next }        }returnNewhead; } Randomlistnode*Copyrandomlist (Randomlistnode*Head) {//Write your code here        if(Head== NULL) {return NULL;        } copynext (head); Copyrandom (head);returnSplitlist (head); }};
Tips:
    • None

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Lintcode-copy List with Random Pointer

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.