1. 程式人生 > >劍指offer(面試題35):複雜連結串列的複製

劍指offer(面試題35):複雜連結串列的複製

/*
* 複雜連結串列的複製 
* 複雜連結串列是指,結點的指標可能不規則地指向另一個結點 
*/
#include<iostream>
using namespace std;

struct ComplexListNode {
    int value;
    ComplexListNode* next;
    ComplexListNode* pSibling;
    ComplexListNode():next(NULL),pSibling(NULL) {

    }
}; 

// 向後複製結點 
void CloneNodes(ComplexListNode* pNode);
// 複製sibling結點 
void ConnectSiblingNodes(ComplexListNode* pNode); // 重新連線,分離原連結串列和複製後的連結串列 ComplexListNode* ReconnectNodes(ComplexListNode* pNode); // 主函式 ComplexListNode* clone(ComplexListNode* pHead); void CloneNodes(ComplexListNode* pRoot) { if(pRoot == NULL) return; ComplexListNode* pNode = pRoot; while
(pNode != NULL) { cout << pNode->value << "->"; ComplexListNode* pNew = new ComplexListNode(); pNew->value = pNode->value; ComplexListNode* tmp = pNode->next; pNew->next = tmp; pNew->pSibling = NULL; pNode->
next = pNew; pNode = pNew->next; } } // coped後的結點的 pSibling都為NULL,若檢測到pSibling非NULL的結點 // 一定是原連結串列上的結點,因此下一個結點一定的複製的結點 void ConnectSiblingNodes(ComplexListNode* pRoot) { if(pRoot == NULL) return; ComplexListNode* pNode = pRoot; while(pNode != NULL) { ComplexListNode* pClone = pNode->next; if(pNode->pSibling != NULL) { // cout << pNode->pSibling->value << endl; ComplexListNode* tmp = pNode->pSibling; pClone->pSibling = tmp->next; } pNode = pClone->next; } } //根據原結點在前,複製的結點在後 // 將連結串列分成兩段一樣的連結串列,如此便得到複雜連結串列的複製 ComplexListNode* ReconnectNodes(ComplexListNode* pRoot) { if(pRoot == NULL) return NULL; int index = 1; ComplexListNode* pNode = pRoot; ComplexListNode* pCloneHead = NULL; ComplexListNode* pCloneNode = NULL; while(pNode != NULL) { if(index % 2 == 0) { if(pCloneHead == NULL) { pCloneHead = pNode; pCloneNode = pCloneHead; } else { pCloneNode->next = pNode; pCloneNode = pCloneNode->next; } } pNode = pNode->next; index ++; } // ComplexListNode* pNode1 = pCloneHead; // cout << "cloned" << endl; // while(pNode1) { // cout << pNode1->value << "->"; // if(pNode1->pSibling) // cout << "(s->" << pNode1->pSibling->value << ")->"; // pNode1 = pNode1->next; // } return pCloneHead; } ComplexListNode* clone(ComplexListNode* pHead) { CloneNodes(pHead); ComplexListNode* pNode = pHead; ConnectSiblingNodes(pHead); // pNode = pHead; // cout << "connected" << endl; // while(pNode) { // cout << pNode->value << "->"; // pNode= pNode->next; // } return ReconnectNodes(pHead); } int main() { ComplexListNode* pHead = new ComplexListNode(); ComplexListNode* p1 = new ComplexListNode(); ComplexListNode* p2 = new ComplexListNode(); pHead->value = 1; p1->value = 2; p2->value = 3; pHead->next = p1; p1->next = p2; pHead->pSibling = p2; p2->pSibling = pHead; ComplexListNode* res = clone(pHead); }