面试题35(剑指offer)--复杂链表的复制

题目:

请实现函数ComplexListNode Clone(ComplexListNode head),复制一个复杂链表。在复杂链表中,每个结点除了有一个Next指针指向下一个结点外,还有一个Sibling指向链表中的任意结点或者NULL。

思路:

  1. 在每个节点后插入要复制的节点
  2. 复制节点间的连接关系
  3. 拆解成两个链表

代码:

	static class ListNode{
        int val;
        ListNode next;
        ListNode sibling;
        ListNode(int val){
            this.val=val;
        }
    }	
	private static ListNode copyList(ListNode a) {
        copy(a);//第一步
        copySecondLink(a);//第二步
        return copySep(a);//第三步
    }

    private static ListNode copySep(ListNode node) {
        ListNode head=node;
        ListNode newHead=null;
        ListNode newNode=null;
        if (head!=null){
            newHead=newNode=head.next;
            head.next=newNode.next;
            head=head.next;
        }
        while (head!=null){
            newNode.next=head.next;
            newNode=newNode.next;
            head.next=newNode.next;
            head=head.next;
        }
        return newHead;
    }

    private static void copySecondLink(ListNode node) {
        ListNode a=node;
        while (a!=null){
            if (a.sibling!=null){
                a.next.sibling=a.sibling.next;
            }
            a=a.next.next;
        }
    }

    private static void copy(ListNode node) {
        ListNode a=node;
        while (a!=null){
            ListNode tmp=a.next;
            ListNode newNode=new ListNode(a.val);
            newNode.next=tmp;
            a.next=newNode;
            a=tmp;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值