-
Notifications
You must be signed in to change notification settings - Fork 0
/
copyRandomList.java
48 lines (48 loc) · 1.26 KB
/
copyRandomList.java
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
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
return head;
}
RandomListNode ret = null, cur2 = null;
RandomListNode cur = head;
while (cur != null) {
RandomListNode tmp = cur.next;
cur.next = new RandomListNode(cur.label);
cur.next.next = tmp;
cur = tmp;
}
cur = head;
cur2 = cur.next;
while (cur != null) {
if (cur.random != null) {
cur2.random = cur.random.next;
}
cur = cur2.next;
if (cur != null) {
cur2 = cur.next;
}
}
cur = head;
cur2 = cur.next;
while (cur != null) {
if (ret == null) {
ret = cur2;
}
cur.next = cur2.next;
cur = cur.next;
if (cur != null) {
cur2.next = cur.next;
cur2 = cur2.next;
}
}
return ret;
}
}