积少成多

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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) {
        
    }
};

============

这个链表节点和普通链表的区别就是,有一个random指针,可以指向链表中的任何元素或者为nullptr

返回产生一个深copy.

思路:

第一遍,对list的每一个节点复制一次放在节点后面,这一次只复制节点的next指针,不复制节点的random指针

第一遍结束后我们的链表节点

    a->b->c->d...  会变成a->fake_a->b->fake_b->c->fake_c->d->d->fake_d....

第二遍再对链表进行random指针复制

第三遍堆链表进行拆分,这样的我们可以将链表分离出来一个新的链表.

 

code如下:

/**
 * 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 *curr = head;
        while(curr){
            RandomListNode *node = new RandomListNode(curr->label);
            node->next = curr->next;
            curr->next = node;
            curr = node->next;
        }///a->f_a->  b->f_b-> ...
        curr = head;
        while(curr){
            if(curr->random){
                curr->next->random = curr->random->next;
            }
            curr = curr->next->next;
        }

        ///partition it into two linktable
        RandomListNode dummy(-1);
        RandomListNode *h = &dummy;
        curr = head;
        while(curr){
            h->next = curr->next;
            curr->next = curr->next->next;
            h = h->next;
            curr = curr->next;
        }
        h->next = nullptr;
        return dummy.next;
    }
};

 

posted on 2016-06-22 16:15  x7b5g  阅读(107)  评论(0编辑  收藏  举报