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.

分析:

我们知道如果是简单的copy List 的话,那么我们只需要从头到尾遍历下来,new出对应个数的Node,并把它们的连接关系设置好就可以了,但是这道题目中每个节点Node出现了Random属性,也就意味着可能当前结点Node所依赖的那个Random对应的结点还没有被创建出来。

如何能够找到新链表每个节点 random 域 所指向的节点呢??

思路: Step 1: 首先指向在原链表的每个节点后面,复制一个新的节点,原链表长度变为 2 倍

   random 指针指向的是 原链表节点 random 指针指向的节点的后面的那个节点

   Step 2: 将链表拆成两个 lists.

下面的代码不是自己写的,自己写的那个不知道为啥,超时了,也不知道错在哪里,这题还有一种用Map的解法,没去看,到时候好好想想········

/**
 * 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 *tHead = head;
        RandomListNode *next = NULL;
        while(tHead)
        {
            next = tHead->next;
            RandomListNode *node = new RandomListNode(tHead->label);
            node->next = tHead->next;
            //node->random = tHead->random;
            tHead->next = node;
            tHead= next;
        }
        tHead = head;
        while(tHead)
        {
            if(tHead->random) tHead->next->random = tHead->random->next;
            tHead = tHead->next->next;
        }
        RandomListNode *retHead = NULL;
        RandomListNode *tRet = NULL;
         
        tHead = head;
        RandomListNode *next2 = NULL;
        while(tHead)
        {
            if(retHead == NULL)
            {  
                next2 = tHead->next->next;
                retHead = tHead->next;
                tRet = retHead;
                tHead->next = next2;
                tHead = next2;
            }
            else
            {
                next2 = tHead->next->next;
                tRet->next = tHead->next;
                tHead->next = next2;
                tHead = next2;
                tRet = tRet->next;
            }
 
        }
        return retHead;
    }
};

  

原文地址:https://www.cnblogs.com/qiaozhoulin/p/4774265.html