复杂链表的复制 我们选取其中的一段代码进行分析
RandomListNode s = new RandomListNode(0);
RandomListNode s1 = s;
while (pHead != null) {
RandomListNode q = pHead.next;
pHead.next = q.next;
q.next = s.next;
s.next = q;
s = s.next;
pHead = pHead.next;
}
这段代码的功能是 将拆分成 A` B` C` D`和 A B C D
补上全部代码
public RandomListNode Clone(RandomListNode pHead) {
RandomListNode p = pHead;
RandomListNode t = pHead;
while (p != null) {
RandomListNode q = new RandomListNode(p.label+10);
q.next = p.next;
p.next = q;
p = q.next;
}
while (t != null) {
RandomListNode q = t.next;
if (t.random != null)
q.random = t.random.next;
t = q.next;
}
RandomListNode s = new RandomListNode(0);
RandomListNode s1 = s;
while (pHead != null) {
RandomListNode q = pHead.next;
pHead.next = q.next;
q.next = s.next;
s.next = q;
s = s.next;
pHead = pHead.next;
}
return s1.next;
}