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.
oj.leetcode.com/problems/copy-list-with-random-pointer/
My code seems fine but is giving a runtime error
Blockquote
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
RandomListNode *t = head, *ans, *tmp ;
while(head){
RandomListNode *node = new RandomListNode(head->label) ;
node->next = head->random ;
head->random = node ;
head = head->next ;
}
head = t ;
while(head){
tmp = head->random ;
if(tmp->next)
tmp->random = tmp->next->random ;
head = head->next ;
}
head = t ;
ans = head->random ;
while(head){
tmp = head->random ;
head->random = tmp->next ;
if(head->next){
tmp->next = head->next->random ;
}else{
tmp->next = NULL ;
}
head = head->next ;
}
return ans ;
}
};
Blockquote
asked
07 Oct, 12:41
wrathtoliar
11●2
accept rate:
0%