-
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
45 lines (39 loc) · 1.27 KB
/
Copy_List_with_Random_Pointer.java
File metadata and controls
45 lines (39 loc) · 1.27 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
package com.leet_code;
public class Copy_List_with_Random_Pointer {
public class ListNode {
int val;
ListNode next;
ListNode random;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; this.random = null;}
}
public ListNode copyRandomList(ListNode head) {// very nice and trickey question to to do, you have just seen this and not solved yet...
if (head == null) return null;
ListNode curr = head;
while (curr != null) {
ListNode newNode = new ListNode(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;
ListNode newHead = head.next;
ListNode newCurr = newHead;
while (curr != null) {
curr.next = newCurr.next;
curr = curr.next;
if (curr != null) {
newCurr.next = curr.next;
newCurr = newCurr.next;
}
}
return newHead;
}
}