0
点赞
收藏
分享

微信扫一扫

复制带随机指针的链表

夏侯居坤叶叔尘 2021-09-21 阅读 34
今日算法
题目描述:
示例 1:

示例 2:

示例 3:

示例 4:

输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 null。

思路一:
代码实现:
class Solution {
    public Map<Node, Node> map = new HashMap();
    public Node copyRandomList(Node head) {
        if (head == null) return head;
        // 当前节点的拷贝节点是否存在
        if (map.get(head) != null) return map.get(head);
        // 拷贝当前节点,并维护关系到hash表中
        Node node = new Node(head.val);
        map.put(head, node);
       // 递归
        node.next = copyRandomList(head.next);
        node.random = copyRandomList(head.random);
        return node;
    }
}
思路二:
代码实现:
class Solution {
    public Map<Node, Node> map = new HashMap();
    public Node copyRandomList(Node head) {
        if (head == null) return head;
        Node cur = head;
        while (cur != null) {
            // 将所有节点拷贝,并以原节点-拷贝节点的关系维护到hash表
            map.put(cur, new Node(cur.val));
            cur = cur.next;
        }
        cur = head;
        while (cur != null) {
            // 替换next节点为拷贝节点
            map.get(cur).next = map.get(cur.next);
            // 替换random节点为拷贝节点
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }
}
思路三:
代码实现:
class Solution {
    public Map<Node, Node> map = new HashMap();
    public Node copyRandomList(Node head) {
        if (head == null) return head;
        Node cur = head;
       while (cur != null) {
           Node temp = cur.next;
           cur.next = new Node(cur.val);
           cur.next.next = temp;
           cur = temp;
       }
       cur = head;
       while (cur != null) {
           Node temp = cur.random;
           if (temp != null)
           cur.next.random = cur.random.next;
           cur = cur.next.next;
       }
    
       cur = head;
       Node cloneCur = head.next;
       Node result = cloneCur;
       while (cloneCur.next != null) {
           Node temp = cur.next.next;
           cur.next = temp;
           cur = temp;
           cloneCur.next = cloneCur.next.next;
           cloneCur = cloneCur.next;
       }
       cur.next = null;
       return result;
    }
}
举报

相关推荐

0 条评论