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:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Lintcode-copy List with Random Pointer