【LeetCode】 138. Copy List with Random Pointer C语言

来源:互联网 发布:淘宝客服话术模板 编辑:程序博客网 时间:2024/06/05 14:42

LeetCode解题心得,欢迎交流! 第三日


/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { *     int label; *     struct RandomListNode *next; *     struct RandomListNode *random; * }; */void clone_nodes(struct RandomListNode *phead)  //复制节点{    struct RandomListNode *pnode=phead;    struct RandomListNode*pcloned=(struct RandomListNode *)malloc(sizeof(struct RandomListNode));        while(pnode != NULL)    {        struct RandomListNode*pcloned=(struct RandomListNode *)malloc(sizeof(struct RandomListNode));        pcloned->label=pnode->label;        pcloned->next=pnode->next;        pcloned->random=NULL;                pnode->next=pcloned;        pnode=pcloned->next;     }}void connect_random_nodes(struct RandomListNode *phead){    struct RandomListNode *pnode=phead;    struct RandomListNode *pcloned=NULL;    while(pnode != NULL)    {        pcloned=pnode->next;        if(pnode->random != NULL)        {            pcloned->random=pnode->random->next;        }        pnode=pcloned->next;    }}struct RandomListNode* reconect(struct RandomListNode *phead){    struct RandomListNode *pnode=phead;    struct RandomListNode *pclone=NULL;    struct RandomListNode *pclone_head=NULL;        if(pnode!=NULL)    {       // pclone=pnode->next;       // pclone_head=pclone;        pclone_head=pclone=pnode->next;        pnode->next=pclone->next;        pnode=pnode->next;    }        while(pnode != NULL)    {        pclone->next=pnode->next;        pclone=pclone->next;        pnode->next=pclone->next;        pnode=pnode->next;    }    return pclone_head;}struct RandomListNode *copyRandomList(struct RandomListNode *head) {    clone_nodes(head);    connect_random_nodes(head);    return reconect(head);}


0 0