题目要求:
一个复杂链表,其结点除了有一个m_pNext指针指向想一个结点外,还有一个m_pSibling指向链表中的任一结点或NULL,其结点的C++定义为:
typedef struct ComplexNode { int m_nValue; ComplexNode *m_pNext; ComplexNode *m_pSibling; }ComplexNode;
下面是一个含有5个结点的该类型的复杂链表。
直线为m_pNext,曲线为m_pSibling指针。为简单起见,指向NULL的指针没有画出。
请完成函数ComplexNode *Clone(ComplexNode *pHead),以复制一个复杂链表。
参考资料:剑指offer第26题。
题目分析:
代码实现:
#include <iostream> using namespace std; typedef struct ComplexListNode { int m_nValue; ComplexListNode *m_pNext; ComplexListNode *m_pSibling; }ComplexListNode; void CloneNodes(ComplexListNode* pHead); void ConnectSiblingNodes(ComplexListNode* pHead); ComplexListNode* ReconnectNodes(ComplexListNode* pHead); // ________ // | |/ //head2:1-->5-->9-->NULL void InitList(ComplexListNode **head) { ComplexListNode *tmp = new ComplexListNode; tmp->m_nValue = 1; *head = tmp; tmp = new ComplexListNode; tmp->m_nValue = 5; tmp->m_pSibling = NULL; (*head)->m_pNext = tmp; ComplexListNode *tmp1 = new ComplexListNode; tmp1->m_nValue = 9; tmp1->m_pSibling = NULL; tmp1->m_pNext = NULL; tmp->m_pNext = tmp1; (*head)->m_pSibling = tmp1; } ComplexListNode* Clone(ComplexListNode* pHead) { CloneNodes(pHead); ConnectSiblingNodes(pHead); return ReconnectNodes(pHead); } 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 ConnectSiblingNodes(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; } void PrintComplexList(ComplexListNode *head) { ComplexListNode *tmp = head; while(tmp) { cout << tmp->m_nValue << "->"; tmp = tmp->m_pNext; } cout << "NULL" << endl; while(head) { if(head->m_pSibling) { cout << head->m_nValue << "->" << head->m_pSibling->m_nValue << endl; } head = head->m_pNext; } cout << "-----------------------------------" << endl; } int main(void) { ComplexListNode *head; InitList(&head); PrintComplexList(head); ComplexListNode *clone = Clone(head); PrintComplexList(clone); return 0; }