码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-05-23 04:12:09      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   c   code   java   

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

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

bubuko.com,布布扣
/*
剑指offer面试题26
*/
#include <iostream>
#include <cstring>

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;
}
bubuko.com,布布扣

 

数据结构-复杂链表的复杂,布布扣,bubuko.com

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

标签:style   class   blog   c   code   java   

原文地址:http://www.cnblogs.com/wn19910213/p/3742332.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!