天天看点

牛客网——剑指offer 复杂链表的复制

题目描述

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

RandomListNode* Clone(RandomListNode* pHead)
    {
        if(pHead == NULL) return NULL;
        
        RandomListNode* tail;
        RandomListNode* head = (RandomListNode*)malloc(sizeof(RandomListNode));
        tail = head;
        head->label = pHead->label;
        head->next = head->random = NULL;
        
        RandomListNode* temp = pHead->next;
        for(; temp != NULL; temp=temp->next)
        {
            RandomListNode* node;
            node = (RandomListNode*)malloc(sizeof(RandomListNode));
            node->label = temp->label;
            tail->next = node;
            tail = node;
            node->next = node->random = NULL;
        }
        
        temp = pHead;
        RandomListNode* node = head;
        for(; temp != NULL; temp=temp->next)
        {
            if(temp->random != NULL)
            {
                RandomListNode *flag1,*flag2;
                flag1 = pHead, flag2 = head;
                while(flag1 != temp->random)
                {
                    flag1 = flag1->next;
                    flag2 = flag2->next;
                }
                node->random = flag2;
            }
            node = node->next;
        }
        
        return head;
    }