剑指offer——面试题26:复杂链表的复制

剑指offer——面试题26:复杂链表的复制

Solution1:
小套路记住就行!!!
根据书上复杂度为 O(n) O ( n ) 的算法写的,此题加深了对于链表指针的理解与应用!

/*
struct RandomListNode {
    int label;
    struct RandomListNode *next, *random;
    RandomListNode(int x) :
            label(x), next(NULL), random(NULL) {
    }
};
*/
class Solution {
public:
    RandomListNode* Clone(RandomListNode* pHead)
    {
        if(pHead == NULL)
            return NULL;
        CloneNodes(pHead);
        ConnectRan(pHead);
        struct RandomListNode* pHead_clone = Get(pHead);
        return pHead_clone;
    }

    void CloneNodes(RandomListNode* pHead){
        struct RandomListNode* pNode = pHead;
        while(pNode != NULL){
            struct RandomListNode* pClone = new RandomListNode(pNode->label);
            pClone->next = pNode->next;
            pNode->next = pClone;
            pNode = pClone->next;
        }
        return;
    }

    void ConnectRan(RandomListNode* pHead){
        struct RandomListNode* pNode = pHead;
        while(pNode != NULL){
            struct RandomListNode* pClone = pNode->next;
            if(pNode->random != NULL){
                pClone->random = pNode->random->next;
            }
            pNode = pClone->next;
        }
        return;
    }

    struct RandomListNode* Get(RandomListNode* pHead){
        struct RandomListNode* pNode1 = pHead, *pHead_Clone = pHead->next;
        struct RandomListNode* pNode2 = pHead_Clone;
        while(pNode1 != NULL){
            pNode1->next = pNode2->next;
            pNode1 = pNode1->next;
            if(pNode1 == NULL)
                break;
            pNode2->next = pNode1->next;
            pNode2 = pNode2->next;
        }
        return pHead_Clone;
    }
};

你可能感兴趣的:(剑指offer题目笔记)