题目:请实现函数ComplexListNode* Clone(ComplexListNode* pHead),复制一个复杂链表。
struct ComplexListNode{
int m_nValue;
ComplexListNode* m_pNext;
ComplexListNode* m_pSibling;
};
思路:分三步,第一步复制对应结点在被复制结点后面,第二步连接Sibling,第三步分离开。
#include <iostream>
using namespace std;
struct ComplexListNode {
int m_nValue;
ComplexListNode *m_pNext;
ComplexListNode *m_pSibling;
};
void CloneNodes(ComplexListNode *pHead) {
ComplexListNode *pNode = pHead;
while (pNode != NULL) {
ComplexListNode *pCloned = new ComplexListNode;
pCloned->m_nValue = pNode->m_nValue;
pCloned->m_pNext = pNode->m_pNext;
pCloned->m_pSibling = NULL;
pNode->m_pNext = pCloned;
pNode = pCloned->m_pNext;
}
}
void CloneSibling(ComplexListNode *pHead) {
ComplexListNode *pNode = pHead;
while (pNode != NULL) {
ComplexListNode *pCloned = pNode->m_pNext;
if (pNode->m_pSibling != NULL)
pCloned->m_pSibling = pNode->m_pSibling->m_pNext;
pNode = pCloned->m_pNext;
}
}
ComplexListNode *ReconnectNodes(ComplexListNode *pHead) {
ComplexListNode *pNode = pHead;
ComplexListNode *pClonedHead = NULL;
ComplexListNode *pClonedNode = NULL;
if (pNode != NULL) {
pClonedHead = pClonedNode = pNode->m_pNext;
pNode->m_pNext = pClonedNode->m_pNext;
pNode = pNode->m_pNext;
}
while (pNode != NULL) {
pClonedNode->m_pNext = pNode->m_pNext;
pClonedNode = pClonedNode->m_pNext;
pNode->m_pNext = pClonedNode->m_pNext;
pNode = pNode->m_pNext;
}
return pClonedHead;
}
ComplexListNode *Clone(ComplexListNode *pHead) {
CloneNodes(pHead);
CloneSibling(pHead);
return ReconnectNodes(pHead);
}
int main() {
ComplexListNode *pHead = NULL;
ComplexListNode *pNode = NULL;
int a;
if (cin >> a) {
pHead = new ComplexListNode;
pNode = pHead;
pNode->m_pSibling = NULL;
pNode->m_nValue = a;
}
while (cin >> a) {
pNode->m_pNext = new ComplexListNode;
pNode = pNode->m_pNext;
pNode->m_pSibling = NULL;
pNode->m_nValue = a;
}
pNode->m_pNext = NULL;
pNode = pHead;
pNode->m_pSibling = pNode->m_pNext->m_pNext;
pNode = pNode->m_pNext;
pNode->m_pSibling = pNode->m_pNext->m_pNext->m_pNext;
ComplexListNode *pdNode = pNode->m_pNext->m_pNext;
pdNode->m_pSibling = pNode;
ComplexListNode *pClonedHead = Clone(pHead);
pNode = pClonedHead;
while (pNode != NULL) {
cout << pNode->m_nValue;
if (pNode->m_pSibling != NULL)
cout << "-" << pNode->m_pSibling->m_nValue << " ";
else
cout << " ";
pNode = pNode->m_pNext;
}
cout << endl;
return 0;
}