Leetcode138. Copy List with Random Pointer复制带随机指针的链表

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的深度拷贝。 

方法一:

class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) 
    {
        if(head == NULL)
            return NULL;
        map<RandomListNode*, RandomListNode*> check;
        RandomListNode *newHead = new RandomListNode(head ->label);
        RandomListNode *node1 = head;
        RandomListNode *node2 = newHead;
        while(node1 ->next)
        {
            check[node1] = node2;
            node2 ->next = new RandomListNode(node1 ->next ->label);
            node1 = node1 ->next;
            node2 = node2 ->next;
        }
        check[node1] = node2;
        node1 = head;
        node2 = newHead;
        while(node1)
        {
            node2 ->random = check[node1 ->random];
            node1 = node1 ->next;
            node2 = node2 ->next;
        }
        return newHead;
    }
};

方法二:

在每个节点后面复制一个节点

/**
 * 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) {
        /**
         * 假设:l1代表原链表中的节点;l2代表新链表中的节点
         */
        RandomListNode *new_head, *l1, *l2;
        if (head == NULL) return NULL;
        
        /**
         * 第一步:在每一个l1后面创建一个l2,并让l1指向l2,l2指向下一个l1;
         */
        for (l1 = head; l1 != NULL; l1 = l1->next->next) {
            l2 = new RandomListNode(l1->label);
            l2->next = l1->next;
            l1->next = l2;
        }
        
        /**
         * 第二步:给l2的random赋值,l1的random的next指向的就是l2的random的目标;
         */
        new_head = head->next;
        for (l1 = head; l1 != NULL; l1 = l1->next->next) {
            if (l1->random != NULL) l1->next->random = l1->random->next;
        }
        
        /**
         * 第三步:需要将整个链表拆成两个链表,具体做法是让l1的next指向后面的后面;
         *         l2的next也指向后面的后面。
         */
        for (l1 = head; l1 != NULL; l1 = l1->next) {
            l2 = l1->next;
            l1->next = l2->next;
            if (l2->next != NULL) l2->next = l2->next->next;
        }
        return new_head;
    }
};

原文地址:https://www.cnblogs.com/lMonster81/p/10433824.html