-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path138.cpp
More file actions
60 lines (56 loc) · 1.58 KB
/
138.cpp
File metadata and controls
60 lines (56 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
//
// 138.cpp
// LeetCode
//
// Created by 张佐玮 on 15/5/21.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Copy List with Random Pointer
//
#include <iostream>
using namespace std;
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 *current = head;
while (current != NULL) {
RandomListNode *shadow = new RandomListNode(current -> label);
shadow -> next = current -> next;
current -> next = shadow;
current = shadow -> next;
}
current = head;
while (current != NULL) {
RandomListNode *shadow = current -> next;
if (current -> random != NULL) {
shadow -> random = current -> random -> next;
}
else {
shadow -> random = NULL;
}
current = shadow -> next;
}
RandomListNode *oldList = head, *newList = head -> next;
current = newList;
while (oldList != NULL) {
oldList -> next = current -> next;
oldList = oldList -> next;
if (oldList != NULL) {
current -> next = oldList -> next;
}
else {
current -> next = NULL;
}
current = current -> next;
}
return newList;
}
};