复杂链表的复制

什么是复杂链表

复杂链表就是,有一个单链表有两个指针,一个指针指向下一个节点,另一个指针指向任何节点,可以是指向空,可以指向自己,可以指向链表中的任意节点。
形如:
这里写图片描述


复杂链表的结构

有两个指针,一个next,一个random,还有一个数据。

struct Node
{
    int _data;//值
    Node* _next;//指向下一个节点的指针
    Node* _random;//指向任意节点的指针
};

复杂链表的复制简单实现

有这样一个复杂链表:
这里写图片描述
分三个部分进行复制:
第一步:
把每个节点复制一个链在原来的那个节点上,新节点的random置空。
这里写图片描述
第二步:将新节点的random链接起来
这里写图片描述
第三步:将两个链表摘开,就是将新复制的节点摘下来,链接起来
这里写图片描述
代码:

Node* ComplexCopy(Node* head)
{
    Node* cur = head;

    //复制新节点连在原来的后面,将新节点的random置空
    while (cur)
    {
        Node* tmp = new Node;
        tmp->_data = cur->_data;
        tmp->_next = cur->_next;
        tmp->_random = NULL;
        cur->_next = tmp;
        cur = tmp->_next;
    }
    //将新节点的random链接起来
    cur = head;
    Node* tmp = NULL;
    while (cur)
    {
        tmp = cur->_next;
        if (cur->_random)
            tmp->_random = cur->_random->_next;
        cur = tmp->_next;
    }
    //摘节点
    cur = head;
    Node* newHead = head->_next;
    Node* next = NULL;
    while (cur)
    {
        next = cur->_next;
        cur->_next = next->_next;
        tmp = cur->_next;
        if (tmp)
        {
            next->_next = tmp->_next;
            next = tmp->_next;
        }
        cur = tmp;
    }
    return newHead;
}

整体代码:

#include <iostream>

using namespace std;

struct Node
{
    int _data;//值
    Node* _next;//指向下一个节点的指针
    Node* _random;//指向任意节点的指针
};

Node* ComplexCopy(Node* head)
{
    Node* cur = head;

    //复制新节点连在原来的后面,将新节点的random置空
    while (cur)
    {
        Node* tmp = new Node;
        tmp->_data = cur->_data;
        tmp->_next = cur->_next;
        tmp->_random = NULL;
        cur->_next = tmp;
        cur = tmp->_next;
    }
    //将新节点的random链接起来
    cur = head;
    Node* tmp = NULL;
    while (cur)
    {
        tmp = cur->_next;
        if (cur->_random)
            tmp->_random = cur->_random->_next;
        cur = tmp->_next;
    }
    //摘节点
    cur = head;
    Node* newHead = head->_next;
    Node* next = NULL;
    while (cur)
    {
        next = cur->_next;
        cur->_next = next->_next;
        tmp = cur->_next;
        if (tmp)
        {
            next->_next = tmp->_next;
            next = tmp->_next;
        }
        cur = tmp;
    }
    return newHead;
}

void TestComplexCopy()//测试
{
    Node* ptr1 = new Node;
    Node* ptr2 = new Node;
    Node* ptr3 = new Node;
    Node* ptr4 = new Node;

    ptr1->_data = 3;
    ptr1->_next = ptr2;
    ptr1->_random = ptr3;

    ptr2->_data = 9;
    ptr2->_next = ptr3;
    ptr2->_random = NULL;

    ptr3->_data = 1;
    ptr3->_next = ptr4;
    ptr3->_random = ptr3;

    ptr4->_data = 5;
    ptr4->_next = NULL;
    ptr4->_random = ptr2;

    ComplexCopy(ptr1);
}

int main()
{
    TestComplexCopy();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值