剑指offer_35_复杂链表的复制_水题

该博客介绍了两种方法实现复杂链表的复制,包括先创建辅助节点的映射法和直接修改原链表的双指针法。这两种方法都涉及到链表操作和随机指针的处理,是数据结构和算法中的常见问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先水过,然后再学题解

import java.util.HashMap;
import java.util.Map;

class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}

class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        // before to new
        Map<Node, Node> map = new HashMap<>();
        Node ans = new Node(head.val);
        map.put(head, ans);
        Node now = ans;
        Node temp = head;
        while (temp.next != null) {
            temp = temp.next;
            now.next = new Node(temp.val);
            now = now.next;
            map.put(temp, now);
        }
        now.next = null;

        now = ans;
        temp = head;
        while (temp != null) {
            now.random = map.get(temp.random);
            now = now.next;
            temp = temp.next;
        }
        return ans;
    }
}

题解的做法就是先在每个节点后加一个相同的辅助节点,借助这些节点来完成拷贝,注意结束的时候要将原链表还原。

class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        for (Node node = head; node != null; node = node.next.next) {
            Node nodeNew = new Node(node.val);
            nodeNew.next = node.next;
            node.next = nodeNew;
        }
        for (Node node = head; node != null; node = node.next.next) {
            Node nodeNew = node.next;
            nodeNew.random = (node.random != null) ? node.random.next : null;
        }
        Node headNew = head.next;
        for (Node node = head; node != null; node = node.next) {
            Node nodeNew = node.next;
            node.next = node.next.next;
            nodeNew.next = (nodeNew.next != null) ? nodeNew.next.next : null;
        }
        return headNew;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/solution/fu-za-lian-biao-de-fu-zhi-by-leetcode-so-9ik5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值