• leetcode 138. Copy List with Random Pointer


    138. Copy List with Random Pointer

    分三步:1.在原有list每个节点的后面增加与原节点值相同的节点

        2.在这些新生成的节点中增加随机节点

        3.将原有的节点和新生成的节点进行分离

    注意:

    if(cur->random)
    randNode = cur->random->next;
    else
    randNode = NULL;

    if(res->next)
    res->next = res->next->next;
    else
    res->next = NULL;

    这两个地方都要判断null的情况。还有这个代码不适合head == NULL的情况,所以一开始也要写为空的返回情况。

    class Solution {
    public:
        Node* copyRandomList(Node* head) {
            if(head == NULL)
                return NULL;
            Node* cur = head;
            while(cur){
                Node* tmp = cur->next;
                Node* newNode = new Node(cur->val);
                cur->next = newNode;
                newNode->next = tmp;
                cur = tmp;
            }
            cur = head;
            while(cur){
                Node* tmp = cur->next;
                Node* randNode;
                if(cur->random)
                    randNode = cur->random->next;
                else
                    randNode = NULL;
                tmp->random = randNode;
                cur = cur->next->next;
            }
            cur = head;
            Node* res = head->next;
            Node* result = head->next;
            while(cur){
                cur->next = cur->next->next;
                if(res->next)
                    res->next = res->next->next;
                else
                    res->next = NULL;
                cur = cur->next;
                res = res->next;
            }
            return result;
        }
    };
  • 相关阅读:
    ios -- 教你如何轻松学习Swift语法(一)
    collectionView,tableView的细节处理
    主流界面搭建原理(类似百思不得姐主界面)
    ios--时间格式化(cell业务逻辑处理)
    test
    Mac下安装Matlab R2015b
    最大奇约数
    编码问题
    最优二叉查找树
    二维数组和二级指针
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/10802932.html
Copyright © 2020-2023  润新知