-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopy_List_with_Random_Pointer.java
More file actions
39 lines (31 loc) · 1.06 KB
/
Copy_List_with_Random_Pointer.java
File metadata and controls
39 lines (31 loc) · 1.06 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
/**
* 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 null;
for(RandomListNode cur = head;cur != null;){
RandomListNode node = new RandomListNode(cur.label);
node.next = cur.next;
cur.next = node;
cur = node.next;
}
for(RandomListNode cur = head;cur != null;){
if(cur.random != null)cur.next.random = cur.random.next;
cur = cur.next.next;
}
RandomListNode result = new RandomListNode(-1);
for(RandomListNode tmp = result,cur = head;cur != null;){
tmp.next = cur.next;
cur.next = cur.next.next;
tmp = tmp.next;
cur = cur.next;
}
return result.next;
}
}