java实现复制带随机指针的链表(力扣138题)

我们要复制以上链表的。重点要保证映射关系的一致

public class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
public class Solution{
    public Node copyRandomList(Node head) {
        Node cur = head;
        Node newNode = null;

        //将新结点插入到对应老结点的后面
        while (cur!=null){
            newNode = new Node(cur.val);
            newNode.next = cur.next;
            cur.next = newNode;
            cur = cur.next.next;
        }

        cur = head;
        //复制random的映射关系
        while (cur!=null){
            //由于之前将新结点插入到了对应老结点后
            //通过找到老结点的random即可找到新结点random指向的结点即为老结点的random的next
            if (cur.random == null){
                cur.next.random = null;
            }else{
                cur.next.random = cur.random.next;
            }
            cur = cur.next.next;
        }

        //拆开老结点和新结点
        cur = head;
        Node newHead = head.next;
        while (cur!=null){
            newNode = cur.next;
            // 改变 cur.next 和 newNode.next
            cur.next = cur.next.next;   // newNode.next
            if (newNode.next != null) {
                newNode.next = newNode.next.next;
            }

            // 让 cur 还指向下一个老结点
            cur = cur.next;
        }
        return newHead;
    }

    public static void main(String[] args) {
        Node head = new Node(7);
        Node n1 = new Node(13);
        Node n2 = new Node(11);
        Node n3 = new Node(10);
        Node n4 = new Node(1);

        head.next = n1;
        head.random = null;
        n1.next = n2;
        n1.random = head;
        n2.next = n3;
        n2.random = n4;
        n3.next = n4;
        n3.random = n2;
        n4.next = null;
        n4.random = head;

        Node node = new Solution().copyRandomList(head);
    }

}

 

这样,我们就完成了深拷贝。 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值