复制含有随机指针节点的链表

import java.util.HashMap;

/**
 * Created by 糖糖 on 2017/8/7.
 */
public class copyLink {
    public static Snode copyLink(Snode head ){
        Snode cur = head;
        HashMap<Snode,Snode> hashMap = new  HashMap<Snode,Snode>();
        while (cur !=null){
            hashMap.put(cur,new Snode(cur.data));
            cur = cur.next;
        }
        cur = head;
        while (cur != null){
            hashMap.get(cur).next = hashMap.get(cur.next);
            hashMap.get(cur).rand = hashMap.get(cur.rand);
            cur = cur.next;
        }
        return hashMap.get(head);
    }

    public  static Snode cpoyLink2(Snode head){
        Snode cur = head;
        Snode next = null;
        //复制链表
        while (cur!=null){
            next = cur.next;
            cur.next = new Snode(cur.data);
            cur.next.next = next;
            cur = next;
        }
        //复制rand关系
        cur = head;
        Snode curcopy = null;
        while (cur != null){
            next = cur.next.next;
            curcopy = cur.next;
            curcopy.rand = cur.rand== null?null:cur.rand;
            cur = next;
        }

        //拆分链表
        cur = head;
        Snode res = head.next;
        while (cur != null){
            next = cur.next.next;
            curcopy = cur.next;
            cur.next = next;
            curcopy.next = next!=null?next:null;
            cur = next;
        }
    return res;
    }

    public  static  void  main(String args[]){
        Snode s1=new Snode(1);
        Snode s2=new Snode(2);
        Snode s3=new Snode(3);

        s1.next = s2;
        s2.next = s3;

        s1.rand = s2;
        s3.rand = s2;
        Snode snode = copyLink(s1);
        Snode snode1 = cpoyLink2(s1);
        System.out.println(snode.rand.data);
        System.out.println(snode1.rand.data);

    }
}
class  Snode{
    int data;
    Snode next;
    Snode rand;
    public Snode(int data){
        this.data=data;
        next = null;
        rand = null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值