复杂链表的复制
题目:实现ComplexLinNode* Clone(ComplexLinNode*pHead),复制一个复杂链表。
分析:必须先pnext后才能进行m_AnyNode
struct ComplexLinNode{ char m_data; ComplexLinNode* m_NextNode; ComplexLinNode* m_AnyNode; }; //1.将要复制的链表连接到链表后面 void CloneNode(ComplexLinNode* pNode) { if (pNode == NULL) return; while (pNode!=NULL) { ComplexLinNode *pCloneNode = new ComplexLinNode; pCloneNode->m_data = pNode->m_data; pCloneNode->m_NextNode = pNode->m_NextNode; pNode->m_NextNode = pCloneNode; pCloneNode->m_AnyNode = NULL; pNode = pCloneNode->m_NextNode; } } //2.将链表的m_AnyNode进行复制 void CopyAnyNode(ComplexLinNode* pNode) { if (pNode == NULL) return; ComplexLinNode * pCloneNode=NULL; while (pNode->m_AnyNode!=NULL) { pCloneNode = pNode->m_NextNode; pCloneNode->m_AnyNode = pNode->m_AnyNode->m_NextNode; pNode = pNode->m_NextNode; //记得别忘了 } } //3.从链表中剥离复制的链表 ComplexLinNode* CopyComplexNode(ComplexLinNode*pNode) { if (pNode == NULL) return; ComplexLinNode *CopyHead = NULL; CopyHead = pNode->m_NextNode; //先初始化复制的头结点 pNode = pNode->m_NextNode; //主要是为了跟踪整个链表的结点 while (pNode!=NULL) { CopyHead->m_NextNode = pNode->m_NextNode->m_NextNode; //选择奇数结点作为copy的结点 pNode = pNode->m_NextNode; } return CopyHead; } //将上面三步合起来 ComplexLinNode* Clone(ComplexLinNode*pHead) { CloneNode(pHead); CopyAnyNode(pHead); return CopyComplexNode(pHead); }