【剑指offer】:复杂链表的复制(第26题)

单链表的基础操作总结
https://blog.csdn.net/hansionz/article/details/80808185
单链表常见面试题总结
https://blog.csdn.net/hansionz/article/details/81608860

问题描述

实现函数pComplexNode CopyComplexList(pComplexNode plist);复制一个复杂链表,在复杂链表中,每个结点除了有一个next指针指向下一个结点外,还有一个sibling指针指向链表中任意一个结点或者是NULL。

定义链表结点

typedef struct ComplexNode
{
    DataType data;//数据域
    struct ComplexNode* next;//指向下一个结点
    struct ComplexNode* random;//指向链表中的随机结点或者为空
}ComNode,*pComplexNode;

思路

(1)在每一个结点的后边连接一个与前面结点数据相同的结点
(2)调整增加结点的random域。(它的random就等于前面结点random->next)
(3)调整整条链表的next域,使之成为两条相同的复杂链表,从而达到复制的结果

这里写图片描述

代码实现

//创建一个复杂结点
pComplexNode BuyComplexNode(DataType d)
{
    pComplexNode newnode = (pComplexNode)malloc(sizeof(ComNode));

    if (newnode != NULL)
    {
        newnode->data = d;
        newnode->next = NULL;
        newnode->random = NULL;
    }
    return newnode;
}
//复杂链表的复制
pComplexNode CopyComplexList(pComplexNode plist)
{
    pComplexNode cur = plist;
    pComplexNode cp = NULL;
    pComplexNode newlist = NULL;
    //①在每一个结点后边追加一个一样的结点5 5 4 4 3 3 2 2 1 1 
    while (cur != NULL)
    {
        pComplexNode tmp = cur->next;
        pComplexNode newnode = BuyComplexNode(cur->data);
        assert(newnode);
        newnode->next = tmp;
        cur->next = newnode;
        cur = tmp;
    }
    //②复制random域
    cur = plist;
    while (cur != NULL)
    {
        cp = cur->next;
        if (cur->random!=NULL)
            cp->random = cur->random->next;
        cur = cp->next;
    }
    //③拆除链表
    cur = plist;
    cp = cur->next;
    newlist = cp;
    while (cur!=NULL)
    {
        cur->next = cp->next;
        if (cur->next !=NULL)
            cp->next = cur->next->next;
        cur = cur->next;
        cp = cp->next;
    }
    return newlist;
}

为了测试方便,我们可以写一个打印函数来打印这个复杂链表

void PrintComplexList(pComplexNode plist)
{
    pComplexNode cur = plist;
    while (cur)
    {
        printf("%d:", cur->data);
        if (cur->random != NULL)
        {
            printf("(%d)-->", cur->random->data);
        }
        else
        {
            printf("(NULL)-->");
        }
        cur = cur->next;
    }
    printf("over\n");
}

下边是测试代码

void TestCopyComplexList()
{
    pComplexNode plist = NULL;
    pComplexNode newlist = NULL;
    pComplexNode p1 = BuyComplexNode(5);
    pComplexNode p2 = BuyComplexNode(4);
    pComplexNode p3 = BuyComplexNode(3);
    pComplexNode p4 = BuyComplexNode(2);
    pComplexNode p5 = BuyComplexNode(1);
    plist = p1;
    p1->next = p2;
    p2->next = p3;
    p3->next = p4;
    p4->next = p5;
    p5->next = NULL;

    p1->random = p3;
    p2->random = p1;
    p3->random = NULL;
    p4->random = p2;
    p5->random = p4;

    PrintComplexList(plist);
    newlist = CopyComplexList(plist);
    PrintComplexList(newlist);
}
int main()
{
    TestCopyComplexList();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hansionz/article/details/80955596
今日推荐