【LeetCode】138.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指向任意一个节点,或者为空。复制这个链表并返回。


思路

           这个题目考察的其实是随机指针的复制,对于原节点random指针所指向的节点,能够巧妙的找到新链表中的对应节点,使新新节点的random指针指向它。这里有一个巧妙的方法,可以迅速找到原节点所对应的新节点。下面以下面这个链表为例。

           每个节点包含的信息为:                                                             

                                     【LeetCode】138.Copy List with Random Pointer 复制带有随机指针的链表_第1张图片                                    

           例子:“X"表示指针指向空

                              【LeetCode】138.Copy List with Random Pointer 复制带有随机指针的链表_第2张图片

           (1)复制给定链表中的每一个节点,将其插入到给定链表中原节点的后面。

           (2)复制random节点。由于新节点就在原节点的后面,因此,依次检测给定链表中的每个节点,若random不为空,则将它的下一个节点(对应新节点)的random指针指向原节点random指针所指节点的下一个节点。

【LeetCode】138.Copy List with Random Pointer 复制带有随机指针的链表_第3张图片

           (3)将该链表差分成新、旧两个链表,返回新链表。

                      原链表:

                             【LeetCode】138.Copy List with Random Pointer 复制带有随机指针的链表_第4张图片

                      新链表:

                               【LeetCode】138.Copy List with Random Pointer 复制带有随机指针的链表_第5张图片

代码

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     struct RandomListNode *next;
 *     struct RandomListNode *random;
 * };
 */
 
struct RandomListNode *copyRandomList(struct RandomListNode *head) {

     if(head==NULL)
        return NULL;
        
    //step1:复制节点,将其插入到原节点的后面
    struct RandomListNode *p=head;
    while(p)
    {
        struct RandomListNode *newNode=(struct RandomListNode*)malloc(sizeof(struct RandomListNode));
        newNode->label=p->label;
        newNode->next=p->next;
        newNode->random=NULL;
        p->next=newNode;
        p=p->next->next;
    }
    
    //step2:复制random指针
    p=head;
    while(p)
    {
        if(p->random)
            p->next->random=p->random->next;
        p=p->next->next;
    }

    //step3:将一个链表拆成两个链表
    p=head;
    struct RandomListNode *newList=p->next;
    while(p)
    {

        struct RandomListNode *p_next=p->next;
        p->next=p_next->next;
        if(p_next->next)//注意
            p_next->next=p_next->next->next;
        else
            p_next->next=NULL;
        p=p->next;
    }
    return newList;
}


你可能感兴趣的:(LeetCode)