数据结构-复杂链表的复杂

题目:请实现函数ComplexListNode*  Clone(ComplexListNode* pHead),复杂一个复杂链表。在复杂链表中,每个节点除了有一个Next指针指向下一个节点外,还有一个Sibling指向链表中的任意节点或者NULL。

分析:第一反应是先复制Next,再复制Sibling。但是这种方式需要两次遍历。时间性不是很好。所以利用一个长链表方式解决时间效率。

/*
剑指offer面试题26
*/
#include 
#include 

using namespace std;

struct ComplexListNode{
    string data;
    ComplexListNode* Next;
    ComplexListNode* Sibling;
};

ComplexListNode* Reconnect(ComplexListNode* head){
    ComplexListNode* p = head;
    ComplexListNode* pClone = p->Next;
    ComplexListNode* pCloneHead = pClone;

    while(pClone->Next != NULL){
        p->Next = pClone->Next;
        p = pClone->Next;
        pClone->Next = p->Next;
        pClone = p->Next;
    }

    return pCloneHead;
}

void CreateNext(ComplexListNode* head){
    ComplexListNode* p = head;
    while(p != NULL){
        ComplexListNode* clone = new ComplexListNode;
        clone->data = p->data;
        clone->Next = p->Next;
        clone->Sibling = NULL;

        p->Next = clone;
        p = clone->Next;
    }
}

void CreateTwoNext(ComplexListNode* head){
    ComplexListNode* p = head;
    while(p != NULL){
        ComplexListNode* pNode = p->Next;
        if(p->Sibling != NULL){
            pNode->Sibling = p->Sibling->Next;
        }
        p = pNode->Next;
    }
}

ComplexListNode* Create(){
    ComplexListNode* pNode1 = new ComplexListNode;
    pNode1->data = 'A';
    ComplexListNode* pNode2 = new ComplexListNode;
    pNode2->data = 'B';
    ComplexListNode* pNode3 = new ComplexListNode;
    pNode3->data = 'C';
    ComplexListNode* pNode4 = new ComplexListNode;
    pNode4->data = 'D';
    ComplexListNode* pNode5 = new ComplexListNode;
    pNode5->data = 'E';

    pNode1->Next = pNode2;
    pNode2->Next = pNode3;
    pNode3->Next = pNode4;
    pNode4->Next = pNode5;
    pNode5->Next = NULL;

    pNode1->Sibling = pNode3;
    pNode2->Sibling = pNode5;
    pNode4->Sibling = pNode2;
    return pNode1;
}

int main(){
    ComplexListNode* Head = Create();
    CreateNext(Head);
    CreateTwoNext(Head);
    ComplexListNode* Clone = Reconnect(Head);

    while(Clone != NULL){
        cout << Clone->data << " ";
        if(Clone->Sibling != NULL){
            cout << "Sibling:" << Clone->Sibling->data << " ";
        }
        Clone = Clone->Next;
    }
    cout << endl;

    return 0;
}

 

转载于:https://www.cnblogs.com/wn19910213/p/3742332.html

你可能感兴趣的:(数据结构与算法,面试)