题目

  • 请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
  • 结点定义
class Node {
    int val;
    Node next;
    Node random;

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

示例

  • 示例1

next和random指向

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

代码

  • 哈希表 O(n)
class Solution {
    public Node copyRandomList(Node head) {
        if(head == null) return null;
        Node cur = head;
        Map<Node, Node> map = new HashMap<>();
        // 3. 复制各节点,并建立 “原节点 -> 新节点” 的 Map 映射
        while(cur != null) {
            map.put(cur, new Node(cur.val));
            cur = cur.next;
        }
        cur = head;
        // 4. 构建新链表的 next 和 random 指向
        while(cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        // 5. 返回新链表的头节点
        return map.get(head);
    }
}

吐槽:我刚开始一直没看懂题,我在想为什么不能同时复制结点的next和random,后来发现结点定义里的构造函数压根没有含参数next和random的构造方法。 ̄﹃ ̄

class Solution {
public:
    ListNode *copyRandomList(ListNode *head) {
        // 把每个节点复制一份插在原结点的后面
        for (auto p = head; p;)
        {
            auto np = new ListNode(p->val);
            auto next = p->next;
            p->next = np;
            np->next = next;
            p = next;
        }
        // 把有 random 指针的老结点赋值给新结点
        for (auto p = head; p; p = p->next->next)
        {
            if (p->random)
                p->next->random = p->random->next;
        }

        auto dummy = new ListNode(-1);
        auto cur = dummy;
        // 把复制的结点拆出来
        for (auto p = head; p; p = p->next)
        {
            cur->next = p->next;
            cur = cur->next;
            p->next = p->next->next;    //  恢复原链表
        }

        return dummy->next;
    }
};

LeetCode详解:这种方式省去了额外的 O(n) 的空间。

题目fu-za-lian-biao-de-fu-zhi-lcof

最后修改:2022 年 01 月 24 日 09 : 41 PM
如果我的文章对你有用,请随意赞赏