-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ138CopyListwithRandomPointer.java
More file actions
51 lines (47 loc) · 1.2 KB
/
Q138CopyListwithRandomPointer.java
File metadata and controls
51 lines (47 loc) · 1.2 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
import util.RandomNode;
/**
* @author ahscuml
* @date 2019/4/17
* @time 21:37
*/
public class Q138CopyListwithRandomPointer {
/**
* 测试函数
* */
public static void main(String[] args) {
// TODO
}
/**
*
* */
public RandomNode copyRandomList(RandomNode head) {
if(head == null) {
return null;
}
RandomNode cur = head;
// 创建新的链表
while(cur != null) {
RandomNode newNode = new RandomNode();
newNode.val = cur.val;
newNode.next = cur.next;
cur.next = newNode;
cur = cur.next.next;
}
cur = head;
// 复制random节点
while(cur != null) {
cur.next.random = cur.random == null ? null : cur.random.next;
cur = cur.next.next;
}
cur = head;
RandomNode dummyHead = cur.next;
// 按照奇偶拆分成两个链表
while(cur != null) {
RandomNode newNode = cur.next;
cur.next = newNode.next;
newNode.next = cur.next == null ? null : newNode.next.next;
cur = cur.next;
}
return dummyHead;
}
}