复杂链表的复制

我们很容易可以想到HashMap的做法,但是O(n)的空间复杂度,对于链表的题而言,明显是一个减分项,因此,可以采用下面的做法:

  1. 复制一个新的节点在原有节点之后,如 1 -> 2 -> 3 -> null 复制完就是 1 -> 1 -> 2 -> 2 -> 3 - > 3 -> null
  2. 从头开始遍历链表,通过 cur.next.random = cur.random.next 可以将复制节点的随机指针串起来,当然需要判断 cur.random 是否存在
  3. 将复制完的链表一分为二。
  4. 同时也要注意将原来的链表还原。
class Solution {
    public Node copyRandomList(Node head) {
        if(head==null){
            return head;
        }
        Node cur = head;
        while(cur!=null){
            Node temp = cur.next;
            Node node = new Node(cur.val);
            cur.next = node;
            node.next = temp;
            cur = temp;
        }
        cur = head;
        while(cur!=null){
            if(cur.random != null){
                cur.next.random = cur.random.next;
            }
            cur = cur.next.next;
        }
        cur = head;
        Node ret = cur.next;
        Node tail = ret;
        while(cur!=null){
            Node temp = cur.next.next;
            if(temp!=null){
                tail.next = temp.next;
                tail = temp.next;
            }
            cur.next = temp;
            cur = temp;
        }
        return ret;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值