题目描述:请实现函数ComplexListNode clone(ComplexListNode head),复制一个复杂链表。在复杂链表中,每个结点除了有一个next 域指向下一个结点外,还有一个sibling 指向链表中的任意结点或者null。
题目解析:
如图结构。
第一步,根据原始链表的每一个结点N创建对应的N’,我们把N’接在N的后面。处理后如图
第二步,假如B指向E,那么B’指向E’。
如图,
第三步,将这个长链表,、分拆成两个链表,奇数结点链接起来就是原链表,偶数链接起来就是复制的链表。
//复杂链表的复制
public static class ComplexListNode {
int value;
ComplexListNode next;
ComplexListNode sibling;
}
//复制结点
public static void cloneNodes(ComplexListNode head) {
while (head != null) {
ComplexListNode temp = new ComplexListNode();
temp.value = head.value;
// 复制结点的next指向下一个要被复制的结点
temp.next = head.next;
// 被复制结点的next指向复制结点
head.next = temp;
// heed指向下一个被复制结点的位置
head = temp.next;
}
}
//设置sibling的链接
public static void setSibling(ComplexListNode head) {
while (head != null) {
head.next.sibling = head.sibling.next;
head = head.next.next;
}
}
//拆分链表,得到原链表和复制链表
public static ComplexListNode getCopyList(ComplexListNode head) {
if (head == null) {
return null;
}
ComplexListNode copyHead = head.next;//复制链表的头结点
// 用于记录当前处理的复制结点
ComplexListNode pointer = copyHead;
head = head.next.next;
while (head != null) {
pointer.next = head;
pointer = pointer.next;
head=head.next.next;
}
return copyHead;
}
public static ComplexListNode clone(ComplexListNode head) {
// 如果链表为空就直接返回空
if (head == null) {
return null;
}
// 先复制结点
cloneNodes(head);
// 再链接sibling字段
setSibling(head);
// 将整个链表拆分,返回复制链表的头结点
return getCopyList(head);
}