zoukankan      html  css  js  c++  java
  • Leetcode 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.

    随机链表的节点数据结构

    struct RandomListNode {
        int label;
        RandomListNode *next, *random;
        RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
    };

    注意本题是对带有随机链表指针的深度拷贝,

    如果数据结构中那个没有随机指针,只需要将链表遍历拷贝一遍即可

    但题目给的数据结构含有指针,拷贝后就必须保有随机指针的关系

    本题通过在每个节点之后插入一个当前节点的拷贝节点,然后让插入的节点保有当前节点随机指针的关系,最后将插入的节点从链表中剥离出来即可

    主要分为3步

    (1)插入拷贝的节点

    (2)复制random指针

    (3)将插入的节点分离出来

    /**
     * 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) {
            //copy list
            RandomListNode *p = head;
            while(p){
                RandomListNode *tmp = new RandomListNode(p->label);
                tmp->next = p->next;
                p->next = tmp;
                p = tmp->next;
            }
            //copy random pointer
            RandomListNode *q = head;
            while(q){
                RandomListNode *tmp = q->next;
                if(q->random){
                    tmp->random = q->random->next;
                }
                q=tmp->next;
            }
            //seperate list
            RandomListNode *dupHead = head == NULL ? NULL : head->next, *cur = head;
            while(cur){
                RandomListNode *tmp = cur->next;
                cur->next = tmp->next;
                if(tmp->next){
                    tmp->next = tmp->next->next;
                }
                cur = cur->next;
            }
            return dupHead;
        }
    };
  • 相关阅读:
    python 函数和函数名的应用
    Python 文件操作
    django报错信息解决方法
    小数据池、代码块以及深浅拷贝
    python 字典的增删改查
    ps 整理通道
    unity 捏脸相关
    Unity3D Blend Shape简析
    unity 乳摇
    爱丽丝的头发是怎么制作的
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3832342.html
Copyright © 2011-2022 走看看