题目:请实现函数clone(ComplexListNode head)复制一个复杂链表。在复杂链表中,每个节点除了有一个next指针指向下一个节点,还有一个sibling指针指向链表中的任意节点或者null。
思路:把问题拆分成三个步骤,第一步先复制所有节点和节点的next,并把复制的节点接在原节点后面,第二步复制节点的sibling,最后再把复制的节点拆分出来。
解决方案:
public class Question35 {
static class ComplexListNode{
int value;
ComplexListNode next;
ComplexListNode sibling;
public ComplexListNode(){}
public ComplexListNode(int value){
this.value = value;
}
}
public static void cloneNodes(ComplexListNode head){
ComplexListNode node = head;
while (node != null){
ComplexListNode cloned = new ComplexListNode();
cloned.value = node.value;
cloned.next = node.next;
cloned.sibling = node.sibling;
node.next = cloned;
node = cloned.next;// 下一个
}
}
public static void connectSiblingNodes(ComplexListNode head){
ComplexListNode node = head;
while (node != null){
ComplexListNode cloned = node.next;
if (node.sibling != null){
cloned.sibling = node.sibling.next;
}
node = cloned.next;
}
}
public static ComplexListNode reconnectNodes(ComplexListNode head){
ComplexListNode node = head;
ComplexListNode clonedHead = null;
ComplexListNode clonedNode = null;
if (node != null){
clonedHead = clonedNode = node.next;
node.next = clonedNode.next;
node = node.next;
}
while (node != null){
clonedNode.next = node.next;
clonedNode = clonedNode.next;
node.next = clonedNode.next;
node = node.next;
}
return clonedHead;
}
public static ComplexListNode clone(ComplexListNode head){
cloneNodes(head);
connectSiblingNodes(head);
return reconnectNodes(head);
}
public static void BuildNodes(ComplexListNode pNode, ComplexListNode pNext, ComplexListNode pSibling)
{
if(pNode != null)
{
pNode.next = pNext;
pNode.sibling = pSibling;
}
}
public static void main(String[] args) {
ComplexListNode pNode1 = new ComplexListNode(1);
ComplexListNode pNode2 = new ComplexListNode(2);
ComplexListNode pNode3 = new ComplexListNode(3);
ComplexListNode pNode4 = new ComplexListNode(4);
ComplexListNode pNode5 = new ComplexListNode(5);
BuildNodes(pNode1, pNode2, pNode3);
BuildNodes(pNode2, pNode3, pNode5);
BuildNodes(pNode3, pNode4, null);
BuildNodes(pNode4, pNode5, pNode2);
System.out.println(clone(pNode1).value);
}
}