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;
        }
    };
  • 相关阅读:
    IOS使用 swizzle 解决一些错误
    Objective-C的hook方案(一): Method Swizzling
    jmeter录制Chrome浏览器https请求进行压力测试
    FIDDLER导出JMX文件,JMETER打开导出的JMX报错的解决方式
    Fiddler的PC端与手机端抓包配置步骤
    初识中间件之消息队列--提高服务性能
    Python虚拟环境配置应用
    jmeter三种阶梯式加压
    JMETER-正则表达式提取与查看变量是否提取正确
    jmeter的线程数,并发用户数,TPS,RPS 关系解说
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5607553.html
Copyright © 2011-2022 走看看