-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path138-Copy-List-with-Random-Pointer.c
54 lines (54 loc) · 1.35 KB
/
138-Copy-List-with-Random-Pointer.c
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
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* struct RandomListNode *next;
* struct RandomListNode *random;
* };
*/
struct RandomListNode *copyRandomList(struct RandomListNode *head) {
struct RandomListNode *newHead = NULL, *tail = NULL, *pNode = head, *temp;
struct RandomListNode *nextPtrArray[100000];
int i = 0;
if (NULL == head)
{
return newHead;
}
while (NULL != pNode)
{
if (NULL == newHead)
{
newHead = (struct RandomListNode*)malloc(sizeof(struct RandomListNode));
tail = newHead;
}
else
{
tail->next = (struct RandomListNode*)malloc(sizeof(struct RandomListNode));
tail = tail->next;
}
tail->label = pNode->label;
temp = pNode;
pNode = pNode->next;
nextPtrArray[i++] = temp->next;
temp->next = tail;
tail->random = temp->random;
tail->next = NULL;
}
pNode = newHead;
while (NULL != pNode)
{
if (NULL != pNode->random)
{
pNode->random = pNode->random->next;
}
pNode = pNode->next;
}
pNode = head;
i = 0;
while (NULL != pNode)
{
pNode->next = nextPtrArray[i++];
pNode = pNode->next;
}
return newHead;
}