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;
        }
    };
     
     
  • 相关阅读:
    Win7下安装iMac系统
    Windows平台cocos2d-x 3.0 android开发环境
    iOS Dev (50)用代码实现图片加圆角
    内部消息 微软中国云计算 内測Azure免费账号 赶紧申请 错过不再有
    android锁屏软件制作
    CF1019E Raining season
    各数据库系统独有函数
    其他函数
    日期时间函数
    字符串函数
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225212.html
Copyright © 2011-2022 走看看