題目:請實(shí)現(xiàn)函數(shù)clone(ComplexListNode head)復(fù)制一個(gè)復(fù)雜鏈表。在復(fù)雜鏈表中衔瓮,每個(gè)節(jié)點(diǎn)除了有一個(gè)next指針指向下一個(gè)節(jié)點(diǎn),還有一個(gè)sibling指針指向鏈表中的任意節(jié)點(diǎn)或者null。
思路:把問題拆分成三個(gè)步驟,第一步先復(fù)制所有節(jié)點(diǎn)和節(jié)點(diǎn)的next骂际,并把復(fù)制的節(jié)點(diǎn)接在原節(jié)點(diǎn)后面,第二步復(fù)制節(jié)點(diǎn)的sibling冈欢,最后再把復(fù)制的節(jié)點(diǎn)拆分出來方援。
解決方案:
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;// 下一個(gè)
}
}
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);
}
}