0
点赞
收藏
分享

微信扫一扫

Leetcode 138. 复制带随机指针的链表

是归人不是过客 2022-03-22 阅读 78

Leetcode 138. 复制带随机指针的链表

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */

struct Node* copyRandomList(struct Node* head) {
    if(head == NULL)
    {
        return NULL;
    }
    struct Node*  cur = head;
    struct Node* curNext = head->next;
    while(cur != NULL)
    {
        struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
        newnode->next = NULL;
        newnode->random = NULL;
        newnode->val = cur->val;
        cur->next = newnode;
        newnode->next = curNext;

        cur = curNext;
        if(curNext != NULL)
        {
            curNext = curNext->next;  
        }
    }

    cur = head;
    curNext = head->next;
    //第二步  设计  radom
    while(cur != NULL)
    {
        if(cur->random == NULL)
        {
            curNext->random = NULL;
        }
        else
        {
            curNext->random = cur->random->next;
        }
        cur = curNext->next;
        if(cur != NULL)
        {
            curNext = cur->next;
        }
    }

    //第三步
    cur = head;
    curNext = head->next;
    struct Node* newHead = NULL;
    struct Node* tail = NULL;
    while(cur != NULL)
    {
        cur->next = curNext->next;
        if(newHead == NULL)
        {
            newHead = curNext;
            tail = newHead;
        }
        else
        {
            tail->next = curNext;
            tail = tail->next;
        }
        cur = cur->next;
        if(cur != NULL)
        {
           curNext = cur->next;
        }

    }
    return newHead;
}
举报

相关推荐

0 条评论