zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】链表题8:35 复杂链表的复制(138. Copy List with Random Pointer)

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    138. 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.
     
    /**
     * 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)
        {
            //第一步:复制结点与next指针
            RandomListNode* cur = head;
            while(cur != nullptr)
            {
                RandomListNode* node = new RandomListNode(cur->label); //构造函数会将next和random指针赋值为null
                node->next = cur->next;//新结点与旧结点连接 
               
                cur->next = node; //旧结点与新结点连接
                cur = node->next; //下个旧结点
            }
           
            //第二步:复制random指针
            cur = head;
            while(cur != nullptr)
            {
                if(cur->random != nullptr) cur->next->random = cur->random->next; //复制random指针 (cur->next为新结点)
                cur = cur->next->next; //下个旧结点
            }
           
            //第三步:拆分链表
            cur = head;
            RandomListNode prehead(0); //创建整个链表的空头结点,方便处理
            prehead.next = head;
            RandomListNode* newcur = &prehead;
            while(cur != nullptr)
            {
                newcur->next = newcur->next->next;//先连接前面的指针,类似题目 328. Odd Even Linked List
                cur->next = cur->next->next;
                
                newcur = newcur->next//更新指针
                cur = cur->next; //cur走在newcur前面,方便判断  
            }
            return prehead.next;
        }
    };
     
     
  • 相关阅读:
    append()、appendChild() 和 innerHTML 的区别
    JS实现动态添加和删除div
    linux下的find文件查找命令与grep文件内容查找命令
    Java 并发基础常见面试题总结
    深入理解HashMap
    JAVA 或与非运算符 与(&)、或(|)、异或(^)
    centos7.x下环境搭建(三)—nodejs安装
    centos7.x下环境搭建(二)—nginx安装
    centos7.x下环境搭建(一)--yum方式安装mysql5.7
    基于vuecli3构建一个快速开发h5 APP的模板
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225212.html
Copyright © 2011-2022 走看看