zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    关于CSS/Grid Layout实例的理解
    关于对CSS position的理解
    接上一条博客
    搬迁声明
    自动化测试流程
    浏览器测试app-H5页面使用appium实现自动化
    RSA加密算法坑:pyasn1-error-when-reading-a-pem-string
    parameter/argument, Attribute/Property区别
    本地mysql用Navicat链接报错 Authentication plugin 'caching_sha2_password' cannot be loaded
    mysql安装忘记root密码,初始化密码
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5607553.html
Copyright © 2011-2022 走看看