(C语言) 复制带随机指针的链表

1.给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。

构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。

例如,如果原链表中有 X 和 Y 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 x 和 y ,同样有 x.random --> y 。

返回复制链表的头节点。

用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:

val:一个表示 Node.val 的整数。
random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为  null 。
你的代码 只 接受原链表的头节点 head 作为传入参数。试题来源:力扣(LeetCode)
代码及其讲解如下:

1.解决这道题的方法很多我们这里使用链接新链表共同遍历的方法进行解决:(总共是三个过程)如下图:

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */
typedef struct Node node;
struct Node* copyRandomList(struct Node* head) {
    if (NULL == head) {
        return NULL;
    }
    node* cur = head;
    while (cur != NULL) {//这个循环用来创建新结点并连接原链表
        node* new_node = (node*)malloc(sizeof(node));
        new_node->val = cur->val;
        new_node->next = cur->next;
        cur->next = new_node;
        cur = new_node->next;
    }
    node* temp = head;
    node* head2 = head->next;
    while (1) {//该循环在遍历原链表的同时跟随原链表一起遍历新链表,找到每一个的
//随机指针random的位置进行相应存储
        //总共遍历所有元素
        node* cur1 = head;
        node* cur2 = head->next;
        while (cur1 != temp->random) {//每个元素的random都要在整段链表中遍历,
//来寻找对应的地址.
            cur1 = cur1->next->next;
            if (NULL == cur1) {
                cur2 = cur2->next;
                break;
            }
            cur2 = cur2->next->next;
        }
        head2->random = cur2;
        temp = temp->next->next;
        if (NULL == temp) {
            break;
        }
        head2 = head2->next->next;
    }
    node* node_1 = head;
    node* node_2 = head->next;
    node* new_head_node = head->next;
    while (node_2->next != NULL) {//遍历完之后新的链表的每个结点的random都指向了
//相应的地方,这时断开链表.
        node_1->next = node_2->next;
        node_2->next = node_1->next->next;
        node_1 = node_1->next;
        node_2 = node_2->next;
    }
    node_1->next = NULL;
    return new_head_node;//返回新链表的首节点地址
}

猜你喜欢

转载自blog.csdn.net/weixin_49312527/article/details/121598778