复杂链表的复制

本文介绍了一种特殊链表——复杂链表的复制方法。这种链表的节点包含next和random两个指针,复制过程分为三步:创建新节点并插入到原节点之后,设置新节点的random指针,最后拆分原链表和新链表。

一个链表的每个节点,有一个指向next指针指向下一个节点,还有一个random指针指向这个链表中的一个随机节点或NULL,现在要求实现复杂这个链表,返回复制后的新链表。

/*    CLNode.h    */

#pragma once

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct CLNode
{
    int data;
    struct CLNode *random;
    struct CLNode *next;
} CLNode;

 CLNode *ComplexCreateNode(int data)
{
    CLNode *node = (CLNode *)malloc(sizeof(CLNode));
    node->data = data;
    node->random = node->next = NULL;
    return node;
}

CLNode *Copy(CLNode *list)
{
    CLNode *cur = list;
    //copy新节点
    while (cur != NULL)
    {
        CLNode *NewNode = ComplexCreateNode(cur->data);
        NewNode->next = cur->next;
        cur->next = NewNode->next;
        cur = cur->next->next;
    }
    //copy新的random
    cur = list;
    while (cur != NULL)
    {
        if (cur->random != NULL)
        {
            cur->next->random = cur->random->next;
        }
        cur = cur->next->next;
    }
    //3.
    cur = list;
    CLNode *newList = cur->next;
    while (cur != NULL)
    {
        CLNode *node = cur->next;
        cur->next = node->next;
        if (cur->next != NULL)
        {
            node->next = cur->next->next;
        }
        else
        {
            node->next = NULL;
        }
        cur = cur->next;
    }
    return newList;
}

void PrintComplexList(CLNode *list)
{
    for (CLNode *cur = list; cur != NULL; cur = cur->next)
    {
        printf("[%d,random(%p)->%d]", cur->data, cur->random, cur->random ? cur->random->data : 0);
    }
    printf("\n");
}

void test()
{
    CLNode *n1 = ComplexCreateNode(1);
    CLNode *n2 = ComplexCreateNode(2);
    CLNode *n3 = ComplexCreateNode(3);
    CLNode *n4 = ComplexCreateNode(4);

    n1->next = n2;
    n2->next = n3;
    n3->next = n4;

    n1->random = n3;
    n2->random = n4;
    n3->random = n1;
    n4->random = n2;

    CLNode *newList = Copy(n1);
    PrintComplexList(n1);
    PrintComplexList(newList);

}
/*    main.c    */

#include "CLNode.h"

int main()
{
    test();
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值