LeetCode Top Interview Questions 138. Copy List with Random Pointer (Java版; Medium)

welcome to my blog

LeetCode Top Interview Questions 138. Copy List with Random Pointer (Java版; Medium)

题目描述
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}

Explanation:
Node 1's value is 1, both of its next and random pointer points to Node 2.
Node 2's value is 2, its next pointer points to null and its random pointer points to itself.
第一次做; 拆链; 本来需要用哈希表记录旧节点和新节点的对应关系, 现在由于直接在链表后面插入新节点, 所以random指针的next就是新节点的random, 这么说太抽象了…; 用一个表示另一个
class Solution {
    public Node copyRandomList(Node head) {
        if(head==null)
            return null;
        Node cur = head, right;
        //在每个节点后面创建新的节点
        while(cur!=null){
            //save next
            right = cur.next;
            //create new node
            cur.next = new Node(cur.val);
            cur.next.next = right;
            //update
            cur = right;
        }
        //补充random指针信息
        cur=head;
        while(cur!=null){
            //核心: 用cur表示cur; 在update阶段, 只update cur即可, 不容易乱
            right = cur.next;
            right.random = cur.random==null? null:cur.random.next;
            //update
            cur = cur.next.next;
        }
        //拆链
        Node newHead = head.next;
        cur = head;
        while(cur!=null){
            //核心:用一个表示另一个
            right = cur.next;
            //
            cur.next = cur.next.next;
            right.next = right.next == null ? null : right.next.next;
            //update
            cur = cur.next;
        }
        return newHead;
    }
}
第一次做; 是用哈希表记录旧节点和新节点的对应关系; 核心: 循环条件
/*
时间复杂度O(N)
空间复杂度: 用哈希表记录旧节点和新节点的话, O(N); 拆链的话,O(1)
两种方法都实现一遍, 巩固一下基础
*/
class Solution {
    public Node copyRandomList(Node head) {
        if(head==null)
            return null;
        HashMap<Node, Node> map = new HashMap<>();
        //遍历两遍链表, 第一遍:创建新链表+记录节点和新节点的对应关系; 第二遍:补充新链表的random信息
        Node newHead = new Node(head.val);
        Node cur=head, tmp=newHead;
        //第一遍遍历链表
        while(cur.next!=null){
            tmp.next = new Node(cur.next.val);
            map.put(cur, tmp);
            //update
            cur = cur.next;
            tmp = tmp.next;
        }
        //单独处理最后一个节点
        map.put(cur, tmp);
        //第二遍遍历链表
        cur=head;
        tmp=newHead;
        while(cur!=null){
            tmp.random = map.get(cur.random);
            //update
            tmp = tmp.next;
            cur = cur.next;
        }
        return newHead;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值