O(N)时间复杂度copy一个含有随机指针的链表

 *
 * 复制含有随机指针的链表
 * 
 * 思路1: 每遍历一次旧节点存入到map一个新的节点(不需要设置),然后依据来节点的指向设置
 * 思路2: 复制节点,由原节点指向,然后拆分
 *
 *   箭头矢代表random指向
 *       ----------->
 *       7 -> 23 -> 3 -> 4 -> 56
 *       <-----
 *
    //思路1: 每遍历一次旧节点存入到map一个新的节点(不需要设置),然后依据来节点的指向设置
    public Node copyLinkWithMap(Node head){
        if(head != null){
            HashMap<Node,Node> map = new HashMap<>();
            Node curr = head;
            //2 ,5 ,1 ,7
            while (curr != null){
                map.put(curr, new Node(curr.val));
                curr = curr.next;
            }
            curr = head;
            while (curr != null){
                map.get(curr).next = map.get(curr.next);
                map.get(curr).rand = map.get(curr.rand);
                curr = curr.next;
            }
            return map.get(head);
        }
        return null;
    }

    //思路2: 复制节点,由原节点指向,然后拆分
    public Node copyLinkWithClone(Node head){
        if(head != null){
            Node curr = head;
            Node next;
            //将copy节点接在元节点下
            while (curr != null){
                next = curr.next;
                //copy一个纯净的节点
                Node cp = new Node(curr.val);
                curr.next = cp;
                cp.next = next;
                curr = next;
            }
            //设置rand指针
            curr = head;
            next = head.next;
            while (curr != null){
                next.rand = curr.rand == null ? null : curr.rand.next;
                next = next.next == null ? null : next.next.next;
                curr = curr.next.next;
            }
            //split
            curr = head;
            next = head.next;
            Node copy = next;
            /*
                箭头矢代表rand指向
                    ----------------->
                    7 -> 7 -> 23 -> 23 -> 3 -> 3 -> 4 -> 4 -> 56 -> 56
                    <----------
             */
            while (curr != null){
                curr.next = next.next;
                curr = curr.next;
                //注意空指针问题
                next.next = next.next == null ? null : next.next.next;
                next = next.next;
            }
            return copy;
        }
        return null;
    }

    private static class Node{
        public int val;
        public Node next;
        public Node rand; //随即指针
        public Node(int val) {
            this.val = val;
        }
    }

  左神算法学习

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值