【剑指offer】复杂链表复制

题目描述

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

示例1

输入

NULL

输出

NULL

思路:

复制这个复杂链表的每个节点,并且跟在原链表的节点后面。如:1->2->3->4->NULL----------->1->1->2->2->3->3->4->4->NULL.

然后复制random的指向,最后把这个链表一分为二。

class Solution {
public:
    RandomListNode* Clone(RandomListNode* pHead)
    {
        if(pHead==NULL)return NULL;
        RandomListNode* cur = pHead;
        RandomListNode* newNode;
        while(cur != NULL)
        {
            newNode = new RandomListNode(cur->label);
            newNode->next = cur->next;
            cur->next = newNode;
            cur = newNode->next;
        }
        
        复制random
        cur = pHead;
        while(cur != NULL)
        {
            newNode = cur->next;
            if(cur->random != NULL)
                newNode->random = cur->random->next;
            cur = cur->next->next;
        }
        
        RandomListNode* newNext;
        RandomListNode* curNext;
        RandomListNode* ret = pHead->next;
        cur = pHead;
        while(cur != NULL)
        {
            newNode = cur->next;
            curNext = newNode->next;
            if(curNext != NULL)
                newNext = curNext->next;
            else
                newNext = NULL;
            cur->next = curNext;
            newNode->next = newNext;
            
            cur = curNext;
        }
        
        return ret;
    }
};

猜你喜欢

转载自blog.csdn.net/yulong__li/article/details/85040623