【LeetCode】链表——复制带随机指针的链表

链接:https://leetcode-cn.com/explore/learn/card/linked-list/197/conclusion/766/
在这里插入图片描述
在这里插入图片描述
思路:先遍历一次原链表,将其拷贝下来(注意拷贝时要新建节点);二次遍历时,添加random索引,刚开始我将原链表中的random值直接赋给拷贝后的链表,后来发现问题所在,要在新拷贝的链表中添加索引,需要参照原链表的相对位置,因此添加了一个findrandom函数实现。

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/
class Solution {
public:
    Node* findrandom(Node* l1,Node* random,Node* l2)
    {
        if(random==NULL) return NULL;
        int step=0;
        Node* find=l1;
        while(find!=random)
        {
            find=find->next;
            step++;
        }
        while(step!=0)
        {
            l2=l2->next;
            step--;
        }
        return l2;
    }
    Node* copyRandomList(Node* head) {
        if(head==NULL) return NULL;
        Node* p=head;
        Node* l=new Node(head->val);
        Node* q=l;       
        while(p->next)
        {
            Node* tmp=new Node(p->next->val);
            q->next=tmp;
            p=p->next;
            q=q->next;
        }
        q->next=NULL;
        q=l;
        p=head;
        while(p)
        {
            if(p->random) q->random=findrandom(head,p->random,l);
            else q->random=NULL;
            q=q->next;
            p=p->next;
        }
        return l;
    }
};

参考:https://leetcode-cn.com/problems/copy-list-with-random-pointer/solution/ke-long-yi-ge-xin-lian-biao-qiu-random-indexyi-don/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值