copy list with random pointer 解题报告

[Problem]

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.

Analysis

问题 理解与解答
概括
思路
提示
复杂度

类似题目 :

总结:

代码:

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
public class {
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
public RandomListNode copyRandomList(RandomListNode head) {
//insert new node to list
if(head == null){
return null;
}
if(head.next == null){
return new RandomListNode(head.label);
}
RandomListNode start = head;
while(head != null){
RandomListNode node = new RandomListNode(head.label);
node.next = head.next;
head.next = node;
head = node.next;
}
//copy random pointer
head = start;
while(head != null){
if(head.random != null){
head.next.random = head.random.next;
}
head = head.next.next;
}
//break
head = start;
RandomListNode head2 = head.next;
RandomListNode start2 = head2;
while(head2.next != null){
head.next = head2.next;
head2.next = head.next.next;
head = head.next;
head2 = head2.next;
// System.out.println("lalala");
}
head.next = null;
return start2;
}
}

[Problem]: