-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathCopy List with Random Pointer.cpp
99 lines (90 loc) · 2.43 KB
/
Copy List with Random Pointer.cpp
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head==NULL)
return NULL;
Node *curr=head;
while(curr!=NULL)
{
Node *nxt = curr->next;
curr->next = new Node(curr->val);
curr->next->next=nxt;
curr=nxt;
}
Node *curr1=head, *curr2=head->next, *nh=head->next;
while(curr1!=NULL)
{
if(curr1->random!=NULL)
curr2->random=curr1->random->next;
else
curr2->random=NULL;
curr1=curr1->next->next;
if(curr2->next==NULL)
curr2=curr2->next;
else
curr2=curr2->next->next;
}
curr1=head, curr2=head->next;
while(curr1!=NULL)
{
curr1->next=curr1->next->next;
if(curr2->next!=NULL)
curr2->next=curr2->next->next;
curr1=curr1->next;
curr2=curr2->next;
}
return nh;
// if(head==NULL)
// return NULL;
// Node *curr=head;
// while(curr!=NULL)
// {
// Node *Next=curr->next;
// Node *temp=new Node(curr->val);
// curr->next=temp;
// temp->next=Next;
// curr=Next;
// }
// Node *curr1=head,*nh=head->next,*curr2=head->next;
// while(curr1!=NULL && curr2!=NULL)
// {
// if(curr1->random!=NULL)
// curr2->random=curr1->random->next;
// else
// curr2->random=NULL;
// curr1=curr1->next->next;
// if(curr2->next!=NULL)
// curr2=curr2->next->next;
// else
// curr2=curr2->next;
// }
// curr2=nh,curr1=head;
// while(curr1!=NULL && curr2!=NULL)
// {
// curr1->next=curr2->next;
// if(curr2->next!=NULL)
// {
// curr2->next=curr1->next->next;
// curr2=curr2->next;
// }
// else
// curr2=curr2->next;
// curr1=curr1->next;
// }
// return nh;
}
};