劍指offer____複雜連結串列的複製
阿新 • • 發佈:2018-11-11
輸入一個複雜連結串列(每個節點中有節點值,以及兩個指標,一個指向下一個節點,另一個特殊指標指向任意一個節點),返回結果為複製後複雜連結串列的head。(注意,輸出結果中請不要返回引數中的節點引用,否則判題程式會直接返回空)
struct RandomListNode { int label; struct RandomListNode *next, *random; RandomListNode(int x) : label(x), next(NULL), random(NULL) { } }; class Solution { public: void CloneNodes(RandomListNode* pHead) { RandomListNode* p = pHead; while(p != NULL) { RandomListNode* newNode = new RandomListNode(p->label); newNode->next = p->next; newNode->random = NULL; // 不能指向p->random p->next = newNode; p = newNode->next; } } void ConnectRanNodes(RandomListNode* pHead) { RandomListNode *p = pHead; while(p != NULL) { RandomListNode* q = p->next; if(p->random != NULL) { q->random = p->random->next; p = q->next; } } } RandomListNode* SplitNodes(RandomListNode* pHead) { RandomListNode* p = pHead; RandomListNode* cloneNodes = NULL; RandomListNode* newNodes = NULL; if(p != NULL) { cloneNodes = newNodes = p->next; p->next = newNodes->next; p = p->next; } while(p != NULL) { newNodes->next = p->next; newNodes = newNodes->next; p->next = newNodes->next; p = p->next; } return cloneNodes; } RandomListNode* Clone(RandomListNode* pHead) { /* if(pHead == NULL) return NULL; CloneNodes(pHead); ConnectRanNodes(pHead); return SplitNodes(pHead); */ if(pHead == NULL) return pHead; RandomListNode* res = new RandomListNode(0); RandomListNode* rnode = res; //複製的連結串列指標 RandomListNode* pnode = pHead; //原來的連結串列指標 while(pnode != nullptr){ RandomListNode* temp = new RandomListNode(pnode->label); book[pnode] = temp; // 建立圖表 rnode->next = temp; rnode = rnode->next; pnode=pnode->next; } pnode = pHead; rnode = res->next; while(pnode != nullptr){ rnode->random = book[pnode->random]; rnode = rnode->next; pnode = pnode->next; } return res->next; } private: map<RandomListNode*,RandomListNode*> book; };