您的位置:首页 > 编程语言 > C语言/C++

C++ 复杂链表的复制

2016-06-05 18:38 155 查看
复杂链表节点结构:



[code=cpp;toolbar:false">struct ComplexNode
{
    ComplexNode(const int& d)
        :_data(d)
        ,_next(NULL)
        ,random(NULL)
    {}
    int _data;            //数据域
    ComplexNode* _next;               //指向下一节点
    ComplexNode* _random;             //指向随机节点
};void UpdateNewNodeRandom(ComplexNode* pHead)
{
ComplexNode* cur = pHead;
while(cur)
{
ComplexNode* next = cur->_next; //指向新节点

if(cur->_random != NULL) //优化:随机指针不为空时,复制
{
next->_random = cur->_random->_next; //复制随机指针
}

cur = next->_next; //下一个要复制的节点
}
}ComplexNode<T>* CopyComplexLinkList(ComplexNode<T>* pHead)
{
if(pHead != NULL) //判空
{
CloneNodes<T>(pHead); //复制节点并连接在其后面
UpdateNewNodeRandom(pHead); //更新新节点的随机指针
return DisconnectNewNode<T>(pHead);/    /拆分链表并返回新链表的头结点
}
return NULL;
}创建复杂链表:ComplexNode* CreatList()
{
ComplexNode* Node1 = new ComplexNode(1);    //创建节点
ComplexNode* Node2 = new ComplexNode(2);
ComplexNode* Node3 = new ComplexNode(3);
ComplexNode* Node4 = new ComplexNode(4);
ComplexNode* Node5 = new ComplexNode(5);

Node1->_next = Node2;       //连接节点
Node2->_next = Node3;
Node3->_next = Node4;
Node4->_next = Node5;

Node1->_random = Node3;    //置_random
Node2->_random = Node4;
Node3->_random = Node1;
Node4->_random = Node5;
Node5->_random = Node2;

return Node1;            //返回头
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: