leetcode刷题-剑指offer-35题

发布时间:2022-06-22 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了leetcode刷题-剑指offer-35题脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

leetcode刷题-剑指offer-35题

题目

请实现 copyRandoMList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null

示例 1:

leetcode刷题-剑指offer-35题

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

示例 2:

leetcode刷题-剑指offer-35题

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

示例 3:

leetcode刷题-剑指offer-35题

输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]

示例 4:

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

解答

新手上路,才学疏浅,望斧正

  1. 先复制节点,再复制节点中的random
  2. 先把每个节点(假设为A)复制一份,放在它的后面(假设为 A1 )。
  3. 再 复制random 即A1的random 为 A的random(假设为B)的后一个节点(假设为B1)
  4. 将新节点(A1 , B1 ,,,)拆出来即可
class Solution3 {
    public Node copyRandomList(Node head) {
        if(head == null){
            return null;
        }

        //在每个节点后复制一份它自己
        Node p = head;
        while (p != null){
            Node tem = new Node(p.val);
            tem.next = p.next;
            p.next = tem;
            p = tem.next;
        }

        //复制ramdom 节点
        p = head;
        while (p != null){
            if(p.random == null) {
                p.next.random = null;
            }else {
                p.next.random = p.random.next;
            }
            p = p.next.next;
        }

        p = head;
        Node res = null;
        Node q=null;
        while (p != null){
            if(res == null){
                res = p.next;
                p.next = p.next.next;
                q = res;
            }else {
                q.next = p.next;
                p.next = p.next.next;
                q = q.next;
            }
            p = p.next;
        }

        return res;

    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的leetcode刷题-剑指offer-35题全部内容,希望文章能够帮你解决leetcode刷题-剑指offer-35题所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。