深度拷贝一个链表

要求:

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点)。
返回一个该链表的深度拷贝。

思路:

1、遍历该链表,复制每一个节点,插入到当前节点的后面.形成如下链表.
1->1'->2->2'....

2、将每个拷贝节点的随机指针域,指向原节点(即拷贝节点的上一个节点)的随即指针域指向(注意随机指针域可能为空)的下一个节点.即1的随机指针域指向3,则1'的随机指针域指向3的下一个指针3'.

3、拆分链表,返回1'->2'->3'...

代码:

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 null;
        RandomListNode runner=pHead;
        RandomListNode copyCat=null;
        //First round: make copy of each nodes
        while(runner!=null){
            copyCat=new RandomListNode(runner.label);
            copyCat.next=runner.next;
            runner.next=copyCat;
            runner=copyCat.next;
        }

        //Second Round: assign random pointers for the copy nodes
        runner=pHead;       
        while(runner!=null){
            copyCat=runner.next;
            //notice random pointers could be null
            copyCat.random=runner.random==null?null:runner.random.next;
            runner=runner.next.next;
        }

        //Third round: restore the original list, and extract the copy list.
        runner=pHead;
        pHead=runner.next;
        while(true){
            copyCat=runner.next;
            runner.next=copyCat.next;
            runner=copyCat.next;
            if(runner==null){
                break;
            }
            else{
               copyCat.next=runner.next;
            }           
        }
        return pHead;
    }
}

 

转载于:https://www.cnblogs.com/sMKing/p/6757738.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值