【剑指Offer】复杂链表的复制

题目

请实现函数ComplexListNode Clone(ComplexListNode pHead),复制一个复杂链表。在复杂链表中,每个结点除了有一个m_pNext指针指向下一个结点外,还有一个m_pSibling指向链表中的任意结点或者NULL。

实现

1
2
3
4
5
6
7
8
9
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;

RandomListNode(int label) {
this.label = label;
}
}
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
public RandomListNode Clone(RandomListNode pHead) {
CloneNodes(pHead);
ConnectSiblingNodes(pHead);
return ReconnectNodes(pHead);
}

private void CloneNodes(RandomListNode pHead) {
RandomListNode node = pHead;

while (node != null) {
RandomListNode clone = new RandomListNode(node.label);
clone.next = node.next;
node.next = clone;
node = clone.next;
}
}

private void ConnectSiblingNodes(RandomListNode pHead) {
RandomListNode node = pHead;

while (node != null) {
if (node.random != null)
node.next.random = node.random.next;

node = node.next.next;
}
}

private RandomListNode ReconnectNodes(RandomListNode pHead) {
RandomListNode node = pHead;
RandomListNode cloneNode = null, cloneHead = null;

if (node != null) {
cloneHead = cloneNode = node.next;
node.next = cloneNode.next;
node = node.next;
}

while (node != null) {
cloneNode.next = node.next;
cloneNode = cloneNode.next;
node.next = cloneNode.next;
node = node.next;
}

return cloneHead;
}