算法---LeetCode 138. 复制带随机指针的链表(剑指offer 35)

55 篇文章 0 订阅
12 篇文章 0 订阅

1. 题目

原题链接

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的 深拷贝。
我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:

val:一个表示 Node.val 的整数。
random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为 null 。

示例 1:

输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]

示例 2:

输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]

2. 题解

2.1 解法1: 使用哈希表 ,两次遍历

  1. 第一次遍历先建立每个节点, 并将原节点作为 key , 新节点作为value 存入哈希表
  2. 第二遍建立指针关系, 有:
    若原节点.next不为null, 新节点.next=map.get(原节点.next);
    若原节点.random不为null, 新节点.random=map.get(原节点.random)

写法1:

    class Solution {
        public Node copyRandomList(Node head) {
            if (head == null) return null;
            Node cur = head;
            HashMap<Node, Node> map = new HashMap<>();
            while (cur != null) {
                map.put(cur, new Node(cur.val));
                cur = cur.next;
            }
            cur = head;
            while (cur != null) {
                map.get(cur).next = map.get(cur.next);
                map.get(cur).random = map.get(cur.random);
                cur = cur.next;
            }
            return map.get(head);
        }
    }

写法2:

    class Solution {
        public Node copyRandomList(Node head) {
            if (head == null) {
                return null;
            }
            Map<Node, Node> map = new HashMap<Node, Node>();
            Node p = head;
            while (p != null) {
                Node newNode = new Node(p.val);
                map.put(p, newNode);
                p = p.next;
            }
            p = head;
            while (p != null) {
                Node copyNode = map.get(p);
                // 可能存在指向为null 的情况, 需要判断
                copyNode.next = p.next == null ? null : map.get(p.next);
                copyNode.random = p.random == null ? null : map.get(p.random);
                p = p.next;
            }
            return map.get(head);

        }


    }

参考:
两种实现+图解 138. 复制带随机指针的链表

2.2 解法2: 递归

模拟图的遍历, 递归函数的作用是建立一个图, 输入为结点值, 输出为结点

    class Solution {
        //  保存是否访问
        Map<Node, Node> map = new HashMap<Node, Node>();
        public Node copyRandomList(Node head) {
            if (head == null) {
                return null;
            }
            if (map.containsKey(head)) {
                return map.get(head);
            }
            // 建立遍历复制结点
            Node newNode = new Node(head.val);
            map.put(head, newNode);
            newNode.next = copyRandomList(head.next);
            newNode.random = copyRandomList(head.random);
            return newNode;
        }
    }

参考:
官方题解

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值