首页 > 代码库 > Copy List with Random Pointer

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.

思路:这题的关键是如何定位next和random。

1.根据原始链表的每个结点N创建对应的克隆结点N‘,并且把N‘链接在N的后面;

2.设置复制出来的结点的random,假设原始链表上的N的random指向结点S,对应其复制出来的N‘是N的next指向的结点,同样S‘也是S的random指向的结点。也就是如果原始链表上的结点N的random指向S,则它对应的复制结点N‘的random指向S的下一节点S‘;

3.把这个长链表拆分成两个链表:把奇数位置的结点用next连接起来就是原始链表,把偶数位置的结点用next连接起来成为复制出来的结点。

/**
 * 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:
    void CloneNodes(RandomListNode *pHead)
    {
        RandomListNode *pNode=pHead;
        while(pNode!=NULL)
        {
            RandomListNode *pCloned=new RandomListNode(pNode->label);
            //pCloned->label=pNode->label;
            pCloned->next=pNode->next;
            pCloned->random=NULL;
            pNode->next=pCloned;
            pNode=pCloned->next;
        }
    }
    void ConnectRandomNodes(RandomListNode *pHead)
    {
        RandomListNode *pNode=pHead;
        while(pNode!=NULL)
        {
            RandomListNode *pCloned=pNode->next;
            if(pNode->random!=NULL)
            {
                pCloned->random=pNode->random->next;
            }
            pNode=pCloned->next;
        }
    }
    RandomListNode *ReconnectNodes(RandomListNode *pHead)
    {
        RandomListNode *pNode=pHead;
        RandomListNode *pClonedHead=NULL;
        RandomListNode *pClonedNode=NULL;
        if(pNode!=NULL)
        {
            pClonedHead=pClonedNode=pNode->next;
            pNode->next=pClonedNode->next;
            pNode=pNode->next;
        }
        while(pNode!=NULL)
        {
            pClonedNode->next=pNode->next;
            pClonedNode=pClonedNode->next;
            pNode->next=pClonedNode->next;
            pNode=pNode->next;
        }
        return pClonedHead;
    }
    RandomListNode *copyRandomList(RandomListNode *head) {
        CloneNodes(head);
        ConnectRandomNodes(head);
        ReconnectNodes(head);
    }
};