• 138. Copy List with Random Pointer


    A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

    Return a deep copy of the list.

    /**
     * Definition for singly-linked list with a random pointer.
     * struct RandomListNode {
     *     int label;
     *     RandomListNode *next, *random;
     *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
     * };
     */
    class Solution {
    public:
        RandomListNode *copyRandomList(RandomListNode *head) {
            
        }
    };

    ============

    这个链表节点和普通链表的区别就是,有一个random指针,可以指向链表中的任何元素或者为nullptr

    返回产生一个深copy.

    思路:

    第一遍,对list的每一个节点复制一次放在节点后面,这一次只复制节点的next指针,不复制节点的random指针

    第一遍结束后我们的链表节点

        a->b->c->d...  会变成a->fake_a->b->fake_b->c->fake_c->d->d->fake_d....

    第二遍再对链表进行random指针复制

    第三遍堆链表进行拆分,这样的我们可以将链表分离出来一个新的链表.

    code如下:

    /**
     * Definition for singly-linked list with a random pointer.
     * struct RandomListNode {
     *     int label;
     *     RandomListNode *next, *random;
     *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
     * };
     */
    class Solution {
    public:
        RandomListNode *copyRandomList(RandomListNode *head){
            RandomListNode *curr = head;
            while(curr){
                RandomListNode *node = new RandomListNode(curr->label);
                node->next = curr->next;
                curr->next = node;
                curr = node->next;
            }///a->f_a->  b->f_b-> ...
            curr = head;
            while(curr){
                if(curr->random){
                    curr->next->random = curr->random->next;
                }
                curr = curr->next->next;
            }
    
            ///partition it into two linktable
            RandomListNode dummy(-1);
            RandomListNode *h = &dummy;
            curr = head;
            while(curr){
                h->next = curr->next;
                curr->next = curr->next->next;
                h = h->next;
                curr = curr->next;
            }
            h->next = nullptr;
            return dummy.next;
        }
    };
  • 相关阅读:
    跟着百度学习之ThinkPHP的认识/初窥
    Apache Rewrite 拟静态
    最新PHPcms9.6.0 任意文件上传漏洞
    最新phpcms v9.6.0 sql注入漏洞分析
    蓝牙攻击-基础篇
    emblog后台拿shell
    绕过云盾找真实IP-找真实IP-绕过CDN
    程序员最重要的品质是什么?
    VC++ 6.0中添加库文件和头文件
    程序的链接与装载
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5607553.html
Copyright © 2020-2023  润新知