package targetOffer;
import targetOffer.PrintTree_23.Node;
public class ComplexCopy_26 {
class Node{
private int value;
Node next;
Node sib;
public Node(int value,Node next,Node sib)
{
this.value=value;
this.next=next;
this.sib=sib;
}
public Node(int i)
{
value=i;
next=null;
sib=null;
}
public Node(){
value=0;
next=null;
sib=null;
}
}
void cloneNodes(Node head)
{
Node newHead=head;
while(newHead!=null)
{
Node newNode=new Node(newHead.value+5,newHead.next,null);
//改变value值,便于和原来的链表进行区分
newHead.next=newNode;
newHead=newNode.next;
}
}
void connectNode(Node head){
Node pNode=head;
Node cloneNode=null;
while(pNode!=null)
{
cloneNode=pNode.next;
if(pNode.sib!=null&&cloneNode!=null)
{
cloneNode.sib=pNode.sib.next;
pNode=cloneNode.next;
}
else
break;
}
}
Node reconnectNode(Node head){
Node pNode=head;
Node result=head.next;
Node cloneNode=null;
while(pNode!=null)
{
cloneNode=pNode.next;
pNode.next=cloneNode.next;
if(cloneNode.next!=null)
{
cloneNode.next=cloneNode.next.next;
//注意,如果cloneNode是最后一个元素,next为空,这句会出现异常
}
else
break;
pNode=pNode.next;
}
return result;
}
Node clone(Node head)
{
cloneNodes(head);
connectNode(head);
return reconnectNode(head);
}
void test(){
Node node1=new Node(1);
Node node2=new Node(2);
Node node3=new Node(3);
Node node4=new Node(4);
node1.next=node2;
node2.next=node3;
node3.next=node4;
node1.sib=node3;
node3.sib=node2;
node2.sib=node4;
node4.sib=node1;
Node temp=node1;
System.out.println("初始链表:\n按next指针排序:");
while(temp!=null)
{
System.out.print(temp.value+"\t");
temp=temp.next;
if(temp==node1)
break;//避免回路,无限循环
}
System.out.println("\n按sib指针排序:");
temp=node1;
while(temp!=null)
{
System.out.print(temp.value+"\t");
temp=temp.sib;
if(temp==node1)
break;
}
//输出复制出的链表
System.out.println("\n复制后链表(value+5):\n按next指针排序:");
Node result=clone(node1);
temp=result;
while(temp!=null)
{
System.out.print(temp.value+"\t");
temp=temp.next;
}
System.out.println("\n按sib指针排序:");
temp=result;
while(temp!=null)
{
System.out.print(temp.value+"\t");
temp=temp.sib;
if(temp==result)
break;//避免回路,无限循环
}
System.out.println();
}
public static void main(String args[])
{
new ComplexCopy_26().test();
}
}
结果:
初始链表:
按next指针排序:
1 2 3 4
按sib指针排序:
1 3 2 4
复制后链表(value+5):
按next指针排序:
6 7 8 9
按sib指针排序:
6 8 7 9