Created
December 6, 2014 11:09
-
-
Save ericpony/d3b8032fabf06f1ba368 to your computer and use it in GitHub Desktop.
Copy List with Random Pointer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list with a random pointer. | |
* struct RandomListNode { | |
* int label; | |
* RandomListNode *next, *random; | |
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
RandomListNode *copyRandomList(RandomListNode *head) { | |
if(head == NULL) return NULL; | |
RandomListNode *p = head; | |
do { | |
RandomListNode *q = p->next; | |
p->next = new RandomListNode(p->label); | |
p->next->next = q; | |
p = q; | |
} while(p != NULL); | |
p = head; | |
do { | |
p->next->random = (p->random == NULL) ? NULL : p->random->next; | |
p = p->next->next; | |
} while(p != NULL); | |
p = head; | |
RandomListNode *r = head->next; | |
for(RandomListNode *q = r;;) { | |
p->next = q->next; | |
p = p->next; | |
if(p == NULL) break; | |
q->next = p->next; | |
q = q->next; | |
} | |
return r; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment