zoukankan      html  css  js  c++  java
  • 【剑指offer25 复杂链表的复制】

    题目描述

    输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
     
    思路:先在每一个链表节点后面复制一个节点,然后插入对应节点的后面
    然后复制随机指针给新节点 注意是 random->next
    最后拆分链表得到结果
    /*
    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 == NULL) {
                return NULL;
            }
             
            RandomListNode *currentNode = pHead;
            //1、复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
            while(currentNode){
                RandomListNode *cloneNode = new RandomListNode(currentNode->label);
                cloneNode->next = currentNode->next ;
                currentNode->next = cloneNode;
                currentNode = cloneNode->next;//往后移动
            }
             
            currentNode = pHead;
            //2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
            while(currentNode) {
                //每个原始点后面的点是我们创建的                random是指向一个随机节点的指针  所以得取rando,->next
                currentNode->next->random = currentNode->random==NULL?NULL:currentNode->random->next;
                currentNode = currentNode->next->next; //移动两位
            }
             
            //3、拆分链表,将链表拆分为原链表和复制后的链表
            currentNode = pHead;
            //最后的结果是从头的下一个元素开始 跳着接
            RandomListNode *pCloneHead = pHead->next;
            RandomListNode *cur_back ;
            while(currentNode->next) { //两个一组 好判断边界  如果四个一组 很容易越界
                cur_back = currentNode->next;
                currentNode->next = cur_back->next;
                currentNode = cur_back;
            }
             
            return pCloneHead;
        }
    };
  • 相关阅读:
    http2
    JMH java基准测试
    java 线程池
    线程中断
    mybatis
    JDBC 线程安全 数据库连接池
    mysql string 列类型
    剖析nsq消息队列目录
    go微服务框架go-micro深度学习-目录
    详说tcp粘包和半包
  • 原文地址:https://www.cnblogs.com/Stephen-Jixing/p/13129515.html
Copyright © 2011-2022 走看看