leetcode---复制带随机值的链表

问题描述

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。要求返回这个链表的 深拷贝。 我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:val:一个表示 Node.val 的整数。random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为  null 。

示例 1:输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]  输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]

示例 2:输入:head = [[1,1],[2,1]]  输出:[[1,1],[2,1]]

示例 3:输入:head = [[3,null],[3,0],[3,null]]  输出:[[3,null],[3,0],[3,null]]

示例 4:输入:head = []  输出:[]

解释:给定的链表为空(空指针),因此返回 null。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/copy-list-with-random-pointer

解题思路

代码描述

struct Node* copyRandomList(struct Node* head) {
	if(head == NULL)
        return NULL;
    //创建新节点,在每一个节点后创建一个新节点,新节点的next域指向原节点的next域,random置空。
    struct Node* pHead = head;
    while(pHead)
    {
        //申请新节点
        struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); 
        newNode->val = pHead->val;
        newNode->random = NULL;
        newNode->next = pHead->next;
        pHead->next = newNode;
        pHead = newNode->next;
    }
    //将新节点的random域设置为与源节点的random域相同
    pHead = head;
    while(pHead && pHead->next)
    {
        if(pHead->random)
            pHead->next->random = pHead->random->next;
        else
            pHead->next->random = NULL;
        pHead = pHead->next->next;
    }
    //将新节点从链表中取出来,连接组成一个新的链表
    pHead = head;
    struct Node* newHead = (struct Node*)malloc(sizeof(struct Node));
    struct Node* tail = newHead;
    while(pHead && pHead->next)
    {
       tail->next = pHead->next;
       pHead->next = pHead->next->next;
       pHead = pHead->next;
       tail = tail->next;
    }
    pHead = newHead->next;
    free(newHead);
    return pHead;
}

猜你喜欢

转载自blog.csdn.net/qq_47406941/article/details/111828485
今日推荐