複雜鏈表的複製

題目描述

輸入一個複雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果爲複製後複雜鏈表的head。(注意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)

 

aa

 

代碼:

/*
struct RandomListNode {
    int label;
    struct RandomListNode *next, *random;
    RandomListNode(int x) :
            label(x), next(NULL), random(NULL) {
    }
};\

while (p!=NULL){
            nex=p->next;
            curr->label=p->label;
            p->next=curr;
            curr->next=nex;
            p=nex;
        }
        a=new RandomListNode(2);
        p=pHead;
        while (p!=NULL){
            nex=p->next;
            nex->random=p->random->next;
            p=nex->next;
        }
        a=pHead->next;
        p=pHead->next;
        while(a!=NULL){
            RandomListNode *cloneNode = a->next;
            a->next=cloneNode->next;
            cloneNode->next=cloneNode->next==NULL?NULL:cloneNode->next->next;
            a=a->next;
            a=a->next;
        }


*/
class Solution {
public:
    RandomListNode* Clone(RandomListNode* pHead)
    {
        if(pHead==NULL)
            return NULL;
        RandomListNode* p,* curr,;
        p=pHead;
        while (p!=NULL){
            curr=new RandomListNode(p->label);
            curr->next=p->next;
            p->next=curr;
            p=curr->next;
        }
        p=pHead;
        while (p!=NULL){
            curr=p->next;
            curr->random=(p->random!=NULL?p->random->next:NULL);
            p=curr->next;
        }
        
        RandomListNode *head = pHead->next;
        RandomListNode *cur = head;
        RandomListNode *pCur = pHead;
        //拆分鏈表
        while(pCur!=NULL){
            pCur->next = pCur->next->next;
            if(cur->next!=NULL)
                cur->next = cur->next->next;
            cur = cur->next;
            pCur = pCur->next;
        }
        return head;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章