分解复杂问题简单化
将问题分为3步,参考P147
结构:
struct ComplexListNode { int m_nValue; ComplexListNode* m_pNext; ComplexListNode* m_pSibling; };
1:复制节点,让N'在N后行成一条新链表
1 void CloneNodes(ComplexListNode* pHead) 2 { 3 ComplexListNode* pNode = pHead; 4 while(pNode != NULL) 5 { 6 ComplexListNode* pCloned = new ComplexListNode(); 7 pCloned->m_nValue = pNode->m_nValue; 8 pCloned->m_pNext = pNode->m_pNext; 9 pCloned->m_pSibling = NULL; 10 11 pNode->m_pNext = pCloned; 12 13 pNode = pCloned->m_pNext; 14 } 15 }
2:遍历新链表,设置N'的m_pSibling的值
1 void ConnectSiblingNodes(ComplexListNode* pHead) 2 { 3 ComplexListNode* pNode = pHead; 4 while(pNode != NULL) 5 { 6 ComplexListNode* pCloned = pNode->m_pNext; 7 if(pNode->m_pSibling != NULL) 8 { 9 pCloned->m_pSibling = pNode->m_pSibling->m_pNext; 10 } 11 12 pNode = pCloned->m_pNext; 13 } 14 }
3:将新链表中的N和N'分离
1 ComplexListNode* ReconnectNodes(ComplexListNode* pHead) 2 { 3 ComplexListNode* pNode = pHead; 4 ComplexListNode* pClonedHead = NULL; 5 ComplexListNode* pClonedNode = NULL; 6 7 if(pNode != NULL) 8 { 9 pClonedHead = pClonedNode = pNode->m_pNext; 10 pNode->m_pNext = pClonedNode->m_pNext; 11 pNode = pNode->m_pNext; 12 } 13 14 while(pNode != NULL) 15 { 16 pClonedNode->m_pNext = pNode->m_pNext; 17 pClonedNode = pClonedNode->m_pNext; 18 19 pNode->m_pNext = pClonedNode->m_pNext; 20 pNode = pNode->m_pNext; 21 } 22 23 return pClonedHead; 24 }
另外一种方法,用map
http://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&tqId=11178&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
1 /* 2 struct RandomListNode { 3 int label; 4 struct RandomListNode *next, *random; 5 RandomListNode(int x) : 6 label(x), next(NULL), random(NULL) { 7 } 8 }; 9 */ 10 /* 11 首先遍历一遍原链表,创建新链表(赋值label和next),用map关联对应结点;再遍历一遍,更新新链表的random指针。(注意map中应有NULL ----> NULL的映射) 12 */ 13 class Solution { 14 public: 15 RandomListNode* Clone(RandomListNode* pHead) 16 { 17 if(pHead==NULL) return NULL; 18 19 map<RandomListNode*,RandomListNode*> m; 20 RandomListNode* pHead1 = pHead; 21 RandomListNode* pHead2 = new RandomListNode(pHead1->label); 22 RandomListNode* newHead = pHead2; 23 m[pHead1] = pHead2; 24 while(pHead1){ 25 if(pHead1->next) pHead2->next = new RandomListNode(pHead1->next->label); 26 else pHead2->next = NULL; 27 pHead1 = pHead1->next; 28 pHead2 = pHead2->next; 29 m[pHead1] = pHead2; 30 } 31 32 pHead1 = pHead; 33 pHead2 = newHead; 34 while(pHead1){ 35 pHead2->random = m[pHead1->random]; 36 pHead1 = pHead1->next; 37 pHead2 = pHead2->next; 38 } 39 return newHead; 40 } 41 };