[编程题]复杂链表的复制

复杂链表的复制

http://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba

/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
public class Solution {
    public RandomListNode Clone(RandomListNode pHead)
    {
        //边界条件
        if(pHead==null){
            return pHead;
        }

        //定义一个指针,指向头结点
        RandomListNode currentNode=pHead;
        //1、复制链表
        while(currentNode!=null){
            //创建源节点相同的复制结点
            RandomListNode copyNode=new RandomListNode(currentNode.label);
            RandomListNode nextNode=currentNode.next;
            copyNode.next=nextNode;
            currentNode.next=copyNode;
            currentNode=nextNode;
        }

        //2、复制链表的复杂指针
        //定义一个指针,指向头结点
        currentNode=pHead;
        while(currentNode!=null){
            //此处需要判断当前结点的任意指针是否为空
          currentNode.next.random=currentNode.random==null?null:currentNode.random.next;
            currentNode=currentNode.next.next;
        }

        //3、将复制到链表与原来的链表拆开
        //定义一个指针指向复制链表的头结点
        currentNode=pHead;
        RandomListNode head=pHead.next;
        while(currentNode!=null){
            RandomListNode currentNodeOfCopy=currentNode.next;
            currentNode.next=currentNodeOfCopy.next;
            //此处需要判断复制的结点是否是最后一个结点
            currentNodeOfCopy.next=currentNodeOfCopy.next==null?null:currentNode.next.next;
            currentNode=currentNode.next;
        }
        return head;
    }
}
全部评论

相关推荐

小浪_Coding:找硬件测试,也可兼顾软测欧, 简历还可以的 ,注意排版,项目写的有条理一点, 然后个人技能多加点, 润色好简历之后就开始沟通海投了,深圳,东莞这边做硬件相关的公司还不少, 医疗类,仪器类的都可以尝试
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务