LeetCode 138--复制带随机指针的链表 ( Copy List with Random Pointer ) ( C语言版 )

题目描述 : 

解题思路 : ( 复杂链表的复制 )  传送门 -- https://blog.csdn.net/ds19980228/article/details/81033631

代码如下 : 

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     struct RandomListNode *next;
 *     struct RandomListNode *random;
 * };
 */

//申请节点
struct RandomListNode * BuyNode(int datum){
    struct RandomListNode * ret=(struct RandomListNode *)malloc(sizeof(struct RandomListNode));
    ret->label=datum;
    ret->next=NULL;
    ret->random=NULL;
    return ret;
}
struct RandomListNode *copyRandomList(struct RandomListNode *head) {
    if(head==NULL)
        return NULL;
    struct RandomListNode *tmp=head;
    //将链表原有的节点复制并且将新创建的节点连接在原有的节点后边
    while(tmp){
        struct RandomListNode * newNode=BuyNode(tmp->label);
        newNode->next=tmp->next;
        tmp->next=newNode;
        tmp=newNode->next;
    }
    tmp=head;
    //将新加入的节点的random指向原有节点->random->next
    while(tmp){
        tmp->next->random=tmp->random==NULL?NULL:tmp->random->next;
        tmp=tmp->next->next;
    }
    struct RandomListNode * ret=head->next;
    struct RandomListNode * tail;
    tmp=head;
    //将创建的新表拆分
    while(tmp){
        tail=tmp->next;
        tmp->next=tail->next;
        if(tail->next)
            tail->next=tail->next->next;
        tmp=tmp->next;
    }
    return ret;
}

猜你喜欢

转载自blog.csdn.net/ds19980228/article/details/82760500