• Leetcode Copy List with Random Pointer


    A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

    Return a deep copy of the list.

    随机链表的节点数据结构

    struct RandomListNode {
        int label;
        RandomListNode *next, *random;
        RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
    };

    注意本题是对带有随机链表指针的深度拷贝,

    如果数据结构中那个没有随机指针,只需要将链表遍历拷贝一遍即可

    但题目给的数据结构含有指针,拷贝后就必须保有随机指针的关系

    本题通过在每个节点之后插入一个当前节点的拷贝节点,然后让插入的节点保有当前节点随机指针的关系,最后将插入的节点从链表中剥离出来即可

    主要分为3步

    (1)插入拷贝的节点

    (2)复制random指针

    (3)将插入的节点分离出来

    /**
     * Definition for singly-linked list with a random pointer.
     * struct RandomListNode {
     *     int label;
     *     RandomListNode *next, *random;
     *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
     * };
     */
    class Solution {
    public:
        RandomListNode *copyRandomList(RandomListNode *head) {
            //copy list
            RandomListNode *p = head;
            while(p){
                RandomListNode *tmp = new RandomListNode(p->label);
                tmp->next = p->next;
                p->next = tmp;
                p = tmp->next;
            }
            //copy random pointer
            RandomListNode *q = head;
            while(q){
                RandomListNode *tmp = q->next;
                if(q->random){
                    tmp->random = q->random->next;
                }
                q=tmp->next;
            }
            //seperate list
            RandomListNode *dupHead = head == NULL ? NULL : head->next, *cur = head;
            while(cur){
                RandomListNode *tmp = cur->next;
                cur->next = tmp->next;
                if(tmp->next){
                    tmp->next = tmp->next->next;
                }
                cur = cur->next;
            }
            return dupHead;
        }
    };
  • 相关阅读:
    P2617 Dynamic Rankings 动态主席树
    P4338 [ZJOI2018]历史 LCT+树形DP
    P3348 [ZJOI2016]大森林
    P3613 睡觉困难综合征 LCT+贪心+位运算
    SP16549 QTREE6
    P3703 [SDOI2017]树点涂色 LCT维护颜色+线段树维护dfs序+倍增LCA
    U19464 山村游历(Wander) LCT维护子树大小
    P4219 [BJOI2014]大融合 LCT维护子树大小
    P2542 [AHOI2005]航线规划 LCT维护双连通分量
    P3950 部落冲突
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3832342.html
Copyright © 2020-2023  润新知