1. 程式人生 > >劍指offer---復雜鏈表的復制

劍指offer---復雜鏈表的復制

結點 ret nec rec int nbsp log style clone

/*
struct RandomListNode {
    int label;
    struct RandomListNode *next, *random;
    RandomListNode(int x) :
            label(x), next(NULL), random(NULL) {
    }
};
*/
class Solution {
public:
    //復制原始鏈表的任一節點N並創建新節點N‘,再把N‘鏈接到N的後邊
    void CloneNodes(RandomListNode* pHead)
    {
        RandomListNode
* pNode=pHead; while(pNode!=NULL) { RandomListNode* pCloned=new RandomListNode(0); pCloned->label=pNode->label; pCloned->next=pNode->next; pCloned->random=NULL; pNode->next=pCloned; pNode
=pCloned->next; } } //如果原始鏈表上的節點N的random指向S,則對應的復制節點N‘的random指向S的下一個節點S‘ void ConnectRandomNodes(RandomListNode* pHead) { RandomListNode* pNode=pHead; while(pNode!=NULL) { RandomListNode* pCloned=pNode->next; if(pNode->random!=NULL) pCloned
->random=pNode->random->next; pNode=pCloned->next; } } //把得到的鏈表拆成兩個鏈表,奇數位置上的結點組成原始鏈表,偶數位置上的結點組成復制出來的鏈表 RandomListNode* ReConnectNodes(RandomListNode* pHead) { RandomListNode* pNode=pHead; RandomListNode* pClonedHead=NULL; RandomListNode* pClonedNode=NULL; //初始化 if(pNode!=NULL) { pClonedHead=pClonedNode=pNode->next; pNode->next=pClonedNode->next; pNode=pNode->next; } //循環 while(pNode!=NULL) { pClonedNode->next=pNode->next; pClonedNode=pClonedNode->next; pNode->next=pClonedNode->next; pNode=pNode->next; } return pClonedHead; } //三步合一 RandomListNode* Clone(RandomListNode* pHead) { CloneNodes(pHead); ConnectRandomNodes(pHead); return ReConnectNodes(pHead); } };

劍指offer---復雜鏈表的復制