【LeetCode & 剑指offer刷题】链表题8:35 复杂链表的复制(138. Copy List with Random Pointer)...

【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 = new cur->next -> next ; //先连接前面的指针,类似题目 328. Odd Even Linked List
            cur->next = cur->next->next;
            
            newcur = newcur -> next //更新指针
            cur = cur -> next ; //cur走在newcur前面,方便判断  
        }
        return prehead . next ;
    }
};
 
 

 

posted @ 2019-01-05 16:55 wikiwen 阅读( ...) 评论( ...) 编辑 收藏
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值