/*
26:> 复杂链表的复制
三步走:
1:A->B >> A->A`->B->B` 复制next链接
2:复制 Sibling链接
3:拆分链表 ,返回cloneList
*/
struct ComplexListNode
{
int m_value;
ComplexListNode* m_pNext;
ComplexListNode* m_pSibling; //指向任意节点
ComplexListNode(int val, ComplexListNode*n = NULL, ComplexListNode*s = NULL)
:m_value(val), m_pNext(n), m_pSibling(s)
{}
};
//1
void CloneNode(ComplexListNode* pHead)
{
if (pHead == NULL)
return;
ComplexListNode* tmp = pHead;
while (tmp != NULL)
{
ComplexListNode* pClone = new ComplexListNode(tmp->m_value, tmp->m_pNext, NULL);
tmp->m_pNext = pClone;
tmp = pClone->m_pNext;//走两步
}
}
//2
void CloneSibling(ComplexListNode* pHead)
{
ComplexListNode* pNode = pHead;
while (pNode!=NULL)
{
ComplexListNode* pClone = pNode->m_pNext;
if (pNode->m_pSibling != NULL)
pClone->m_pSibling = pNode->m_pSibling;
pNode = pClone->m_pNext;
}
}
//3
ComplexListNode* Depart(ComplexListNode* pHead)
{
ComplexListNode* pNode = pHead;
ComplexListNode* pCloneHead = NULL;
ComplexListNode* pCloneNode = NULL;
if (pNode != NULL)
{
pCloneNode = pCloneHead = pNode->m_pNext;
pNode->m_pNext = pCloneNode->m_pNext;
pNode = pCloneNode->m_pNext;
}
while (pNode!=NULL)
{
pCloneNode->m_pNext = pNode->m_pNext ;
pCloneNode= pCloneNode->m_pNext;
pNode->m_pNext = pCloneNode->m_pNext;
pNode = pNode->m_pNext;
}
return pCloneHead;
}
ComplexListNode* Clone(ComplexListNode* pHead)
{
CloneNode(pHead);
CloneSibling(pHead);
return Depart(pHead);
}
//void test()
//{
// ComplexListNode* E = new ComplexListNode(5,NULL,NULL);
// ComplexListNode* D = new ComplexListNode(4,E,NULL);
// ComplexListNode* C = new ComplexListNode(3,D,NULL);
// ComplexListNode* B = new ComplexListNode(2,C,NULL);
// ComplexListNode* A = new ComplexListNode(1,B, D);
//
// E->m_pSibling = C;
//
// /************************************************************************/
//
// ComplexListNode *pCloneHead = Clone(A);
//
// while (pCloneHead != NULL)
// {
// cout << pCloneHead->m_value<<" ";
// if (pCloneHead->m_pSibling != NULL)
// cout << pCloneHead->m_pSibling->m_value << " ";
//
// cout << endl;
// pCloneHead = pCloneHead->m_pNext;
//
// }
//}
复杂链表的复制
最新推荐文章于 2023-06-16 13:23:16 发布
本文详细介绍了如何通过三步实现复杂链表的复制,包括复制节点、复制兄弟节点链接以及拆分原始与副本链表。使用了自定义结构体来定义复杂链表,并通过Clone、CloneSibling和Depart函数实现了复制过程。
摘要由CSDN通过智能技术生成