1. 程式人生 > >【劍指offer】複雜連結串列複製

【劍指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;
    }
};