zoukankan      html  css  js  c++  java
  • 剑指offer 复杂链表的复制 (有向图的复制)

    时间复杂度O(3N)


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    /*
    struct RandomListNode {
        int label;
        struct RandomListNode *next, *random;
        RandomListNode(int x) :
                label(x), next(NULL), random(NULL) {
        }
    };
    */
    class Solution {
    public:
        RandomListNode* Clone(RandomListNode* pHead)
        {
            if(!pHead)return NULL;
            RandomListNode *result,*cur,*tmp;
            cur=pHead;
            while(cur)//每个节点 后面复制一个自己
            {
                tmp=new RandomListNode(cur->label);
                tmp->next=cur->next;
                cur->next=tmp;
                cur=tmp->next;
            }
            cur=pHead;
            tmp=cur->next;
            while(cur)//复制random连接
            {
                if(cur->random!=NULL)
                    tmp->random=cur->random->next;
                cur=tmp->next;
                if(cur!=NULL)//链表尾部的处理
                    tmp=cur->next;
            }
            //拆分两个表
            cur=pHead;
            result=cur->next;
            tmp=result;
            while(cur)
            {
                cur->next=tmp->next;
                cur=cur->next;
                if(cur!=NULL)//链表尾部的处理
                {
                    tmp->next=cur->next;
                    tmp=tmp->next;
                }
            }
            return result;
        }
    };

  • 相关阅读:
    最短路详解
    树状数组基础
    并查集初步
    python shell的交互模式和文本编辑模式
    基于python的selenium自动化测试环境搭建
    Nagios基本搭建
    mysql错误代码对照表较完整
    搭建phpMyAdmin
    Cent OS 7 搭建MySQL
    详解封装源码包成RPM包
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/5285129.html
Copyright © 2011-2022 走看看