当前位置: 首页>移动开发>正文

(✌)粤嵌—202458—随机链表的复制

代码实现:

struct Node* copyRandomList(struct Node *head) {
    if (head == NULL) {
        return NULL;
    }
    // 第一步:复制节点,并将复制节点插入到原节点的旁边
    struct Node *p = head;
    while (p) {
        struct Node *temp = malloc(sizeof(*temp));
        temp->val = p->val;
        temp->next = p->next;
        temp->random = NULL; // 先设为 NULL,后面再处理 random 指针
        p->next = temp;
        p = p->next->next;
    }

    // 第二步:复制 random 指针
    p = head;
    while (p) {
        if (p->random) {
            p->next->random = p->random->next; // 直接复制 random 指针关系
        }
        p = p->next->next;
    }

    // 第三步:拆分链表
    struct Node *newHead = head->next;
    p = head;
    while (p) {
        struct Node *temp = p->next;
        p->next = temp->next;
        if (temp->next) {
            temp->next = temp->next->next; // 避度两步,避免回到原链表
        }
        p = p->next;
    }
    return newHead;
}

https://www.xamrdz.com/mobile/4n61948271.html

相关文章: