[LeetCode]Copy List with Random Pointer &Clone Graph 复杂链表的复制&图的复制

/**
 * 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) {
        //每个节点指向其复制链表对应的节点,从而可以快速定位该节点
        if(!head)return NULL;
        RandomListNode *p,*q;
        p=head;
        while(p){
            q=new RandomListNode(p->label);
            q->next=p->next;
            p->next=q;
            p=q->next;
        }
        p=head;
        while(p){
            q=p->next;
            if(p->random)
                q->random=p->random->next;
            p=q->next;
        }
        p=head;
        RandomListNode*head2=p->next;
        q=head2;
        while(p){
            p->next=q->next;
            p=p->next;
            if(p){
                q->next=p->next;
                q=q->next;
            }
        }
        return head2;
    }
};


Clone Graph

 :

类似的,对于图的复制,必须找到一种可以对新图中节点进行映射,能快速定位新节点的地址,从而使新节点指向新节点。这里采用map映射。考虑到图节点的label可能重复(本题不重复),而节点地址不重复,所以以新旧节点为键值对。

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    map<UndirectedGraphNode*,UndirectedGraphNode*>mp;
    map<UndirectedGraphNode*,UndirectedGraphNode*>::iterator bg;
    UndirectedGraphNode* dfs(UndirectedGraphNode*p){
        if(!p)return NULL;
        if((bg=mp.find(p))!=mp.end())
            return bg->second;
        UndirectedGraphNode *q;
        mp[p]=q=new UndirectedGraphNode(p->label);
        for(int i=0,m=p->neighbors.size();i<m;++i){
            q->neighbors.push_back(dfs(p->neighbors[i]));
        }
        return q;
    }
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if(!node)return NULL;
        dfs(node);
        return mp[node];
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值