41:复制复杂链表

复制复杂链表

实现函数ComplexListNode(ListNode node)复制一个链表

public class Offer41 {
   public static void main(String[] args) {
       ComplexListNode node1 = new ComplexListNode(1);
       ComplexListNode node2 = new ComplexListNode(2);
       ComplexListNode node3 = new ComplexListNode(3);
       ComplexListNode node4 = new ComplexListNode(4);
       ComplexListNode node5 = new ComplexListNode(5);
       ComplexListNode node6 = new ComplexListNode(6);
       node1.next = node2;
       node2.next = node3;
       node3.next = node4;
       node4.next = node5;
       node5.next = node6;
       node6.next = null;
       node1.sibling = node4;
       node2.sibling = node5;
       node3.sibling = node6;
       node4.sibling = node1;
       node5.sibling = node2;
       node6.sibling = node3;
       ComplexListNode(node1);
   }


   public static ComplexListNode ComplexListNode(ComplexListNode node){
       if(node==null)return null;
       ComplexListNode temp = node;
       //形成A-'A'-B-'B'...链表
       while (node!=null){
           ComplexListNode complexListNode = new ComplexListNode(node.value);
           complexListNode.next = node.next;
           node.next = complexListNode;
           node = complexListNode.next;
       }
       //给sibling进行赋值
       node = temp;
       while (node!=null){
           if(node.sibling!=null){
               node.next.sibling = node.sibling.next;
           }
           node = node.next.next;
       }
       //拆分成两条链表
       node = temp;
       ComplexListNode head = temp;
       temp = node.next;

       node.next = temp.next;
       node = node.next;
       while (node!=null){
           temp.next = node.next;
           temp = temp.next;
           node.next = temp.next;
           node = node.next;
       }

       return head;
   }

}
class  ComplexListNode{
   int value;
   ComplexListNode next;
   ComplexListNode sibling;

   public ComplexListNode(int value) {
       this.value = value;
   }
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页