Leecode之随机链表的复制

简介: Leecode之随机链表的复制

一.题目及剖析

https://leetcode.cn/problems/copy-list-with-random-pointer/

这个题目的意思就是拷贝一份复杂链表,难点在于它的random指针所指向的空间与拷贝下来的链表之间缺少一种联系,当然可以用遍历链表的方式通过value去找那块空间,不过时间复杂度太高.

二.思路引入

所以这道题的重中之重就是怎样让拷贝链表地random和原链表以及之间产生联系

我们不妨引入这样一种方法,在原链表每个节点的后面创建一个新的节点,该节点的值与上个节点相同,这样我们新节点的random指向的空间就是原节点的random指向空间的下一块空间,最后再将新节点从原链表中截下来,并恢复原链表.

三.代码引入

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */
typedef struct Node Node;
struct Node* copyRandomList(struct Node* head) {
  Node* pcur = head;
    //在每个节点后面再插入一个相同的节点
    while(pcur)
    {
        Node* copy = (Node*)malloc(sizeof(Node));
        copy->val = pcur->val;
        copy->next = pcur->next;
        pcur->next = copy;
        pcur = pcur->next->next;
    }
    pcur = head;
    //处理random指针指向的节点(copy->random == pcur->random->next)
    while(pcur)
    {
        Node* copy = pcur->next;
        if(pcur->random == NULL)
        copy->random = NULL;
        else
        copy->random = pcur->random->next;
        pcur = pcur->next->next;
    }
    pcur = head;
    Node* newhead = NULL, * newtail = NULL;
    //将对应节点放到新链表中
    while(pcur)
    {
        Node* next = pcur->next;
        pcur->next = next->next;
        if(newtail == NULL)
        newhead = newtail = next;
        else
        {
            newtail->next = next;
            newtail = newtail->next;
        }
        pcur = pcur->next;
    }
    return newhead;
}
相关文章
|
5月前
Leecode之反转链表
Leecode之反转链表
|
5月前
Leecode之合并两个有序链表
Leecode之合并两个有序链表
|
5月前
Leecode之分割链表
Leecode之分割链表
|
5月前
Leecode之环形链表进阶
Leecode之环形链表进阶
|
5月前
Leecode之相交链表
Leecode之相交链表
|
5月前
Leecode之环形链表
Leecode之环形链表
|
索引
【LeeCode】每日一题:复制带随机指针的链表
【LeeCode】每日一题:复制带随机指针的链表
59 0
|
Java C++
Leecode 876. 链表的中间结点
Leecode 876. 链表的中间结点
45 0
Leecode 24. 两两交换链表中的节点
Leecode 24. 两两交换链表中的节点
51 0
|
4月前
|
存储 SQL 算法
LeetCode力扣第114题:多种算法实现 将二叉树展开为链表
LeetCode力扣第114题:多种算法实现 将二叉树展开为链表