剑指offer25_复杂链表的复制_题解

复杂链表的复制

题目描述

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

分析

方案一:哈希

利用哈希表的查询特点,考虑构建 原链表节点新链表对应节点 的键值对映射关系,再遍历构建新链表各节点的 nextrandom 引用指向即可。

/**
时间复杂度:O(N)
两轮遍历链表,使用 O(N) 时间。
空间复杂度:O(N)
哈希表 dic 使用线性大小的额外空间。
**/
class Solution
{
public:
    RandomListNode *Clone(RandomListNode *pHead)
    {
        if (pHead == nullptr)
            return nullptr;
        RandomListNode *cur = pHead;
        unordered_map<RandomListNode *, RandomListNode *> mp;
        // 复制各节点,并建立“原节点->新节点”的Map映射
        while (cur)
        {
            mp[cur] = new RandomListNode(cur->label);
            cur = cur->next;
        }
        cur = pHead;
        // 构建新链表的next和random指向
        while (cur != nullptr)
        {
            mp[cur]->next = mp[cur->next];
            mp[cur]->random = mp[cur->random];
            cur = cur->next;
        }
        // 返回新链表的头节点
        return mp[pHead];
    }
};

方法二:拼接+拆分

①第一步:根据原始链表的每个节点 \(N\) 创建对应的 \(N'\) ,再把 \(N'\) 链接到 \(N\) 的后面

②第二步:设置复制出来的节点的 \(random\) 指针

③第三步:把这个长链表拆分成两个链表:把奇数位置的节点用 \(next\) 指针链接起来就是原始链表,把偶数位置的节点用 \(next\) 指针链接起来就是复制出来的链表

/**
时间复杂度:O(N)
三轮遍历链表,使用 O(N) 时间。
空间复杂度:O(1)
节点引用变量使用常数大小的额外空间。
**/
class Solution
{
public:
    RandomListNode *Clone(RandomListNode *pHead)
    {
        if (pHead == nullptr)
            return nullptr;
        RandomListNode *cur = pHead;
        // 1.复制各节点,并构建拼接链表
        while (cur != nullptr)
        {
            RandomListNode *tmp = new RandomListNode(cur->label);
            tmp->next = cur->next;
            cur->next = tmp;
            cur = tmp->next;
        }
        // 2.构建各新节点的random指向
        cur = pHead;
        while (cur != nullptr)
        {
            if (cur->random != nullptr)
                cur->next->random = cur->random->next;
            cur = cur->next->next;
        }
        // 3.拆分两链表
        cur = pHead->next;
        RandomListNode *pre = pHead, *res = pHead->next;
        while (cur->next != nullptr)
        {
            pre->next = pre->next->next;
            cur->next = cur->next->next;
            pre = pre->next;
            cur = cur->next;
        }
        pre->next = nullptr; //单独处理原链表尾节点
        return res;          //返回新链表头节点
    }
};
posted @ 2020-12-25 12:16  RiverCold  阅读(47)  评论(0编辑  收藏  举报