-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopy-list-with-random-pointer
More file actions
46 lines (44 loc) · 1.01 KB
/
Copy-list-with-random-pointer
File metadata and controls
46 lines (44 loc) · 1.01 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
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
if (head==null) return null;
Node curr=head;
while(curr!=null){
Node newNode= new Node(curr.val);
newNode.next=curr.next;
curr.next=newNode;
curr=newNode.next;
}
curr=head;
while(curr!=null){
if(curr.random!=null){
curr.next.random=curr.random.next;
}
curr=curr.next.next;
}
curr=head;
Node newHead=head.next;
Node newCurr=newHead;
while(curr!=null){
curr.next=newCurr.next;
curr=curr.next;
if(curr!=null){
newCurr.next=curr.next;
newCurr=newCurr.next;
}
}
return newHead;
}
}