LeetCode — Copy List with Random Pointer 解题报告

转载请注明:http://blog.csdn.net/ict2014/article/details/17577191

原题如下:

    

题目解析:

     这道题目是“复杂链表的复制”。很经典的一道题目,可以从网上进行搜索,比如可以参考这篇文章:复杂链表复制

我们按照传统的做法进行解题。总共分为三步:

     1、申请结点并且连接成一个链表

     2、random pointer的赋值

     3、拆分链表成两个链表


题目代码:

/**
 * 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) {
       RandomListNode* new_head = NULL;
       if(head == NULL){
           return new_head;
       }
       
       //copy and connect
       CopyAndConnect(new_head, head);
       //set the random
       SetRandom(head);
       //split into two list
       SplitToTwoLists(head);
       
       return new_head;
    }
    
    //copy the list to new list
    //connect the two lists
    void CopyAndConnect(RandomListNode* &new_head,
                        RandomListNode* head){
       bool first = true;
       RandomListNode* next, *new_node;
       while(head != NULL){
           next = head->next;
           new_node = new RandomListNode(head->label);
           new_node->next = next;
           head->next = new_node;
           if(first){
               new_head = new_node;
               first = false;
           }
           head = next;
       }
    }
    
    //set the random
    void SetRandom(RandomListNode* head){
        while(head != NULL){
            if(head->random != NULL){
                head->next->random = head->random->next;
            }
            head = head->next->next;
        }
    }
    
    //split into two list
    void SplitToTwoLists(RandomListNode* head){
        RandomListNode* next;
        while(head != NULL){
            next = head->next;
            head->next = next->next;
            if(next->next == NULL){
                next->next = NULL;
            }else{
                next->next = next->next->next;
            }
            head = head->next; 
        }
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值