Welcome to 发呆鱼.|

发呆鱼

园龄:3年4个月粉丝:1关注:0

leetcode刷题-剑指offer-35题

leetcode刷题-剑指offer-35题

题目

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

示例 1:

img

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

示例 2:

img

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

示例 3:

img

输入: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;

    }
}

本文作者:发呆鱼

本文链接:https://www.cnblogs.com/dyiblog/p/15778620.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   发呆鱼  阅读(19)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起