【leetcode】138. 随机链表的复制

leetcode题目链接 138. 随机链表的复制
【leetcode】138. 随机链表的复制_第1张图片

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */
typedef struct Node Node;
Node* copyRandomList(Node* head) {
    if (head != NULL) {
        // 1.在cur后面copy一份cur
        for (Node* cur = head; cur != NULL; cur=cur->next->next) {
            Node* newnode = (Node*)malloc(sizeof(Node));
            newnode->val = cur->val;
            newnode->next = cur->next;
            cur->next = newnode;
        }
        // 2.将每个copy的节点的random指针补充完整
        for (Node* cur = head; cur != NULL; cur=cur->next->next) {
            Node* newnode = cur->next;
            newnode->random = cur->random ? cur->random->next : NULL;
        }
        // 3.将copy的节点依次取下
        Node* newhead = head->next;
        for (Node* cur = head; cur != NULL; cur = cur->next) {
            Node* newnode = cur->next;
            cur->next = cur->next->next;
            newnode->next = newnode->next ? newnode->next->next : NULL;
        }
        return newhead;
    }
    return NULL;
}

你可能感兴趣的:(C语言,刷题,C++,leetcode,链表,算法,数据结构,c语言)