-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopyListwithRandomPointer.h
More file actions
63 lines (53 loc) · 1.58 KB
/
CopyListwithRandomPointer.h
File metadata and controls
63 lines (53 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**************************************
* Author : luoshikai
* Version : 1.0
* Date : 2013-10-23
* Email : [email protected]
*************************************/
/**************************************
* 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.
*************************************/
/**
* 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)
{
RandomListNode *res = NULL;
if (head == NULL) return res;
RandomListNode *ptr = head;
while (ptr != NULL)
{
RandomListNode *temp = new RandomListNode(ptr->label);
temp->next = ptr->next;
ptr->next = temp;
ptr = temp->next;
}
ptr = head;
while (ptr != NULL)
{
RandomListNode *temp = ptr->next;
if (ptr->random != NULL) temp->random = ptr->random->next;
ptr = temp->next;
}
ptr = head;
res = head->next;
while (ptr != NULL)
{
RandomListNode *temp = ptr->next;
ptr->next = temp->next;
ptr = ptr->next;
if (ptr != NULL) temp->next = ptr->next;
}
return res;
}
};