算法系列之-复制含有随机指针的链表

package it.list;

import java.util.HashMap;
import java.util.Map;

/**
 * @项目名称:util
 * @类名称:RandNode @类描述:随机指针复制

 */
public class RandNode {

    public static RNode copyList(RNode rNode) {
        RNode cur = rNode;
        Map<RNode, RNode> map = new HashMap<>();
        while (cur != null) {
            map.put(cur, new RNode(cur.value));
            cur = cur.next;
        }
        cur = rNode;
        while (cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).rand = map.get(cur.rand);
            cur = cur.next;
        }
        return map.get(rNode);

    }

    public static RNode copyList2(RNode rNode) {
        RNode head = rNode;
        RNode next = null;
        // 复制链接节点
        while (head != null) {
            next = head.next;
            head.next = new RNode(head.value);
            head.next.next = next;
            head = next;
        }
        head = rNode;
        RNode node = null;
        // 复制rand指针
        while (head != null) {
            next = head.next.next;
            node = head.next;
            node.rand = head.rand != null ? head.rand.next : null;
            head = next;
        }

        // 拆分
        head = rNode;
        RNode res = rNode.next;
        while (head != null) {
            next = head.next.next;
            node = head.next;
            node.next = next;
            node.next = next != null ? next.next : null;
            head = next;
        }
        return res;

    }

    public static void main(String[] args) {
        RNode rNode = new RNode(1);
        RNode rNode2 = new RNode(2);
        RNode rNode3 = new RNode(3);
        RNode rNode4 = new RNode(4);
        RNode rNode5 = new RNode(5);
        rNode.next = rNode2;
        rNode.rand = rNode3;
        rNode2.next = rNode3;
        rNode2.rand = rNode3;
        rNode3.next = rNode4;
        rNode3.rand = rNode;
        rNode4.next = rNode5;
        rNode4.rand = rNode2;
        rNode5.next = null;
        rNode5.rand = rNode3;
        RNode copyList = copyList2(rNode);

        while (copyList != null) {
            System.out.print(copyList.value + "->" + copyList.rand.value + "||");
            copyList = copyList.next;
        }
    }

}

class RNode {

    RNode next;
    RNode rand;
    int value;

    public RNode(int value) {
        this.value = value;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值